What is the difference between File and FileInfo in C#? - c#

I've been reading that the static methods of the File Class are better used to perform small and few tasks on a file like checking to see if it exists and that we should use an instance of the FileInfo Class if we are going to perform many operations on a specific file.
I understand this and can simply use it that way blindly, but I would like to know why is there a difference?
What is it about the way they work that make them suitable for different situations? What is the point of having this two different classes that seem do the same in different ways?
It would be helpful if someone could answer at least one of this questions.

Generally if you are performing a single operation on a file, use the File class. If you are performing multiple operations on the same file, use FileInfo.
The reason to do it this way is because of the security checking done when accessing a file. When you create an instance of FileInfo, the check is only performed once. However, each time you use a static File method the check is performed.

The methods of the File and FileInfo classes are similar, but they differ in that the methods of the File class are static, so you need to pass more parameters than you would for the methods of the FileInfo instance.
You need to do this because it operates on a specific file; for example, the FileInfo.CopyTo() method takes one parameter for the destination path that's used to copy the file, whereas the File.Copy() method takes two parameters for the source path and the destination path."
References
http://aspfree.com/c/a/C-Sharp/A-Look-at-C-Sharp-File-and-FileInfo-Classes/1/
http://intelliott.com/blog/PermaLink,guid,ce9edbdb-6484-47cd-a5d6-63335adae02b.aspx

The File.Exists will perform much faster than a new FileInfo(filePath).Exists - especially over a network and provided the files actually exist. This is because File.Exists will only check for existence of the file, whereas a new FileInfo(filePath).Exists first constructs a FileInfo object, which contains all the properties (dates, size etc) of the file (if it exists).
In my experience with this, even checking for the existence of 10 files over the network is noticeably faster (ie 20ms vs 200ms) by using File.Exists.

File is optimized for one-off operations on a file, FileInfo is optimized around multiple operations on the same file, but in general there isn't that much difference between the different method implementations.
If you want to compare the exact implementations, Use Reflector to look at both classes.

A FileInfo may be needed to deal with Access Control properties. For the rest it is a Static versus Instance choice and you can pick what is convenient.

FileInfo is an instance of a file thus representing the file itself. File is a utility class so can work with any file

FileInfo:
Need to instantiate before using
Contains instance methods
Cache Info about the File and you need to call Refresh every time to get the latest info about the File
File:
No need to instantiate
Contains static methods
Do not cache, so you get latest info every time you use it.
src:
FileInfo
File

Yes, and one of the reason could be is, as Nag said Files is a utility class and hence no instance is required to be created. Same time, as File being utility class, each time require security check.
On other hand FileInfo requires instance to be created, and that point it uses security check. Thus, now performing multiple operation using FileInfo will not invoke security checks.

Recently I faced problem with File.Exist, I hate this function. After than I've used Fileinfo class Exist function then my program works correct.
Actually what happen in development enviornment File.Exist works well but when it goes to live environment this function is blocking the file object due to that reason I am getting the error access denied and not able to use the file.
This is my learning.
I will never used File.Exist method best is to create the object and then use it. Be aware to use static methods.

The major difference between File class and FileInfo class is that
Both members of the File and FileInfo class are decorated with the [System.Security.SecurityCritical] and [System.Security.SecuritySafeCritical] attribute but File class has 'multiple security checks' as compared to FileInfo class (Read Here) and the check is performed each time when you call a static member of the File class.
When you create an instance of FileInfo, the check is performed only once.
Apart from these, other minor differences are that File is a static type class whereas FileInfo is an instance type class.
Therefore to access the members of FileInfo class you need to create an instance whereas in File class you can directly access its members without the need to create an instance.
If you are performing multiple operations on the same file, it can be more efficient to use FileInfo instance methods instead of the corresponding static methods of the File class.
However, File class provides more methods as compared to FileInfo class.
Note: Either the SecurityCriticalAttribute attribute or the SecuritySafeCriticalAttribute attribute must be applied to code for the code to perform security-critical operations.

Related

Best way to make methods easily callable and configurable by third party

I have a solution with several self-contained classes and methods. For example, I have:
a FileDownloader class that has multiple different methods that download files based on passing in a URL or multiple URLs
a DataTransformations class that has multiple methods that transform data depending on what is necessary for a given operation
a FileWriter class that writes some data to some kind of file type or file format
etc.
I have all of these classes as .cs files under the same solution. I can consider the order of executions for some specific operation and call the methods from MAIN in the correct order and it produces the output that I expect. I will eventually, however, need to call some or all of these methods in many different configurations for several different processes and I don't know how to do that. I know how to pass in configuration through command line arguments, but even that requires the specific order and number of methods called stays the same between processes. This is not tenable because I will not need to download files in some instances and I will not need to transform data in some instances etc. I am very new to .NET development and I have not yet wrapped my head around how to truly decouple these classes from each other. Do I have to deploy a different solution for each class? I would like to just be able to say "call file downloader with these parameters" and then "perform data transformations based on these parameters" basically like steps in an execution job.
Dirty Answer, Compile as a library and then add a reference in whatever project you want to use those methods for. you can then call the methods by name (LibraryName).MethodName(Parameters). of course you will need to always have that DLL in whatever other project need access. if you have any questions on how to do this let me know.

Where to place delegate definitions

Every time I have made a delegate definition, I think about where to put it in a project.
Do I put it in the file with the class consuming the delegate? I would think NO, as it could be interesting for other classes to use the same delegate.
Do I put it in the file with the delegate object? I would think NO, as the general idea usually is, that several diferent classes and/or methods can be used for that.
Do I put it in a file of its own ? I would think NO because - well - it just seems plain silly to have a one line file in projects that potentially holds hundreds if not thousands of files.
Do I collect delegates in larger utility type files ? Hmmmm.... don't like.
So what do I do ?

How to tell different classes to save to the same folder during execution of a program?

I have a program where the typical use-case is to create a session and during this session, to perform some sequential numeric calculations, where the result of each calculation is passed as parameter to the subsequent one.
It is a requirement that each intermediate numeric result MUST be saved to disk, so that the following situation is achieved:
At the beginning of the session, a new, uniquely-named folder is created;
Each calculation is sequentially run, each by a different classe, and at the end of each calculation, some file with intermediate result is saved in that folder;
At the end of the session (and after the program is closed), the folder could be optionally accessed from the filesystem, and all files would be there.
My doubt is:
"how do I tell each class where is the folder it is supposed to save?".
It is ok for us, architecturally, to have IO code in the classes, but the use of a "global" value containing the path, versus passing the path in the constructor to every class, versus another, more sensible, solution, is confusing me.
Passing the path to the constructor of each class is what's known as dependency injection, and it's generally considered the preferable way of doing things, at least at a simple level. The ideal solution would be to inject an instance of a file writer interface into each class as that way you can test each class using a mock writer. That is more complex to implement though. Either way, dependency injection is being used.
By using a global value, you couple all parts of your code to that value. Such coupling should be avoided as it leads to brittle code that can easily break when changes are made. The reason being, that in a large system it can be hard to identify all dependencies on a global item and thus understand the consequences of changing it.

What is the difference between System.IO.File and System.IO.FileInfo

Why there are two class for the almost same purpose System.IO.File and System.IO.FileInfo.
System.IO.File provides static members related to working with files, whereas System.IO.FileInfo represents a specific file and contains non-static members for working with that file.
From MSDN:
Because all File methods are static,
it might be more efficient to use a
File method rather than a
corresponding FileInfo instance method
if you want to perform only one
action. All File methods require the
path to the file that you are
manipulating.
The static methods of the File class
perform security checks on all
methods. If you are going to reuse an
object several times, consider using
the corresponding instance method of
FileInfo instead, because the security
check will not always be necessary.
In general they do two very different things:
System.IO.File - getting/working with any file
System.IO.FileInto - getting/working with (including metadata) a particular file
Granted they do share a few methods with the same purpose, but for the most part they have very different purposes/scenarios that they serve best.

How to get Classes and methods from a .cs file using Reflections in C#.?

How to get the classes that are available in a '.cs' file.? Like we can get the classes and methods in an Assembly using,
Assembly.GetTypes() and Type.GetMethods()
to get the Class and methods in an Assembly.
Similarly how to get all the classes present within a C# file(.cs file).? I need to get the classes in a .cs file from which i can easily get the methods within them and further details like parameters of methods etc.
Short of using a C# parser, there's no direct way of doing it. You could compile the .cs file using CSharpCodeProvider (which only works if the file compiles on its own and you can tell all the referenced assemblies to the compiler) and use reflection on the resulting assembly.
I recommend you to use a parser generator tool to generate a quick c# parser, you can use Antlr.
Also you can check this and this
The compiler erases all notions of a codefile from your code as it is compiled. That being said perhaps it is possible to retrieve the information you want from debugging symbols if they are available in your assembly.
From with in the class you can always call
this.GetType()
or outside the class you can always call
obj.GetType()
however when you compile an application, which is required for reflection to work, you can no longer get their definitions by file.
I've done this previously by invoking the C# compiler, compiling the C# file and then using reflection on the outputted type. This is possible if the C# file is a standalone file and doesn't have any dependencies.
However, the correct way would be to use a parser - something which isn't that easy to do. There are a couple of options available, MinosseCC being one of them.
Incidentally, C# 5.0 will make it a lot easier to compile code on the fly by being able to compile a String and getting back executable code. Can't wait for this - it's sure to confuse everyone that reads my code.
First of all, there is no such thing as the .cs file in which a class is defined. A class can be marked as partial and parts can be defined in several .cs files.
When you compile with debug information, the filenames for each method remain in the assembly (for each line of the source file, the corresponding IL commands are tagged).
Unfortunately, I don't know an easy way to get to that information from within the running application (without parsing the assembly file manually).
If you are safe calling the method, you can call it and in parallel construct a stack trace (from another thread) - in the StackFrame object you will find the original file name. But this is slow (as you have to call every method just to find that the filename is different) and risky (what if the method formats your hard drive?).
So, the only way you could go is try to parse the .cs file with a parser like AntLR yourself.

Categories

Resources