What are special functionalities in File class which are not available in FileInfo class and vice versa?
File and FileInfo overlap a lot, but they are designed differently.
- File is a static utility class that works directly with file paths.
- FileInfo is an instance class that represents one specific file object and caches some metadata.
Here are the differences.
| Functionality | File | FileInfo |
| Static methods | Yes | No |
| Object instance | No | Yes |
| Works with file path directly | Yes | No |
| Keeps file metadata in object | No | Yes |
| Refresh metadata | No | Yes Refresh() |
| Access file properties | Limited | Yes |
| Reuse same file reference | No | Yes |
Things in File that are not available in FileInfo
- Helper methods to read entire file
These convenience methods exist only on File.
string[] lines = File.ReadAllLines(path);
byte[] bytes = File.ReadAllBytes(path);
Equivalent with FileInfo requires opening streams manually.
- Helper methods to write entire file
File.WriteAllLines(path, lines);
File.WriteAllBytes(path, bytes);
File.AppendAllText(path, "More");
FileInfo does not provide these shortcut methods.
- Copy/Delete/Move without object creation
File.Move(src, dest);
File.Delete(path);
With FileInfo:
var fi = new FileInfo(path);
fi.Delete();
fi.MoveTo(dest);
- Attribute/time static helpers
File.SetCreationTime(path, DateTime.Now);
No direct equivalent static-style usage in FileInfo.
Things in FileInfo that are not available in File
- File metadata properties
Console.WriteLine(fi.Length);
Console.WriteLine(fi.DirectoryName);
Console.WriteLine(fi.Extension);
Console.WriteLine(fi.IsReadOnly);
File doesn't expose these as properties.
- Metadata refresh
Useful if file changed after object creation.
File has no concept of refreshing because it doesn't store state.
- Open methods bound to file
fi.OpenWrite();
fi.OpenText();
fi.CreateText();
fi.AppendText();
File has equivalents, but not object-oriented reuse.
- Cached repeated access
Console.WriteLine(fi.Length);
Console.WriteLine(fi.CreationTime);
Console.WriteLine(fi.LastWriteTime);
One object can be reused.
With File, every call requires path lookup again.
Practical rule
- Use File → quick operations (read/write/copy/delete).
- Use FileInfo → when working with one file repeatedly or inspecting metadata.
Example:
string text = File.ReadAllText(path);
// Better with FileInfo
FileInfo file = new FileInfo(path);
if (file.Length > 1024)
{
Console.WriteLine(file.Name);
}
No comments:
Post a Comment