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

Viewed 33619

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.

10 Answers

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

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