Thursday, June 18, 2026

C# Functionalities in File class which are not available in FileInfo class and vice versa

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

  1. Helper methods to read entire file

These convenience methods exist only on File.

string text = File.ReadAllText(path);
string[] lines = File.ReadAllLines(path);
byte[] bytes = File.ReadAllBytes(path);

Equivalent with FileInfo requires opening streams manually.

  1. Helper methods to write entire file
File.WriteAllText(path, "Hello");
File.WriteAllLines(path, lines);
File.WriteAllBytes(path, bytes);
File.AppendAllText(path, "More");

FileInfo does not provide these shortcut methods.

  1. Copy/Delete/Move without object creation
File.Copy(src, dest);
File.Move(src, dest);
File.Delete(path);
With FileInfo:
var fi = new FileInfo(path);
fi.Delete();
fi.MoveTo(dest);
  1. Attribute/time static helpers
File.SetAttributes(path, FileAttributes.Hidden);
File.SetCreationTime(path, DateTime.Now);

No direct equivalent static-style usage in FileInfo.

Things in FileInfo that are not available in File

  1. File metadata properties
FileInfo fi = new FileInfo(path);
Console.WriteLine(fi.Length);
Console.WriteLine(fi.DirectoryName);
Console.WriteLine(fi.Extension);
Console.WriteLine(fi.IsReadOnly);

File doesn't expose these as properties.

  1. Metadata refresh
fi.Refresh();

Useful if file changed after object creation.

File has no concept of refreshing because it doesn't store state.

  1. Open methods bound to file
fi.OpenRead();
fi.OpenWrite();
fi.OpenText();
fi.CreateText();
fi.AppendText();

File has equivalents, but not object-oriented reuse.

  1. Cached repeated access
FileInfo fi = new FileInfo(path);
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:

// Better with File
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

Hot Topics