tags:

views:

884

answers:

5

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 2 different classes that seem do the same in different ways ?

It would be helpful if someone could answer at least one of this questions.

+3  A: 

"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."

http://www.aspfree.com/c/a/C-Sharp/A-Look-at-C-Sharp-File-and-FileInfo-Classes/1/

http://www.intelliott.com/blog/PermaLink,guid,ce9edbdb-6484-47cd-a5d6-63335adae02b.aspx

madcolor
+19  A: 

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.

John Rasch
+1 this explanation is more relevant in this case..imo
Stan R.
This answer, while arguably correct, I find highly misleading. Please elaborate on .NET stack walking security checks vs. OS ACL security checks. Both constitute "the security checking done when accessing a file".
Ben Voigt
+1  A: 

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.

Franci Penov
A: 

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

Nag
A: 

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.

div