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

Solution 1:

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.

Solution 2:

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

Solution 3:

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.

Solution 4:

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.

Solution 5:

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.