File Class and FileInfo Class

Overview

  • FileInfo
    • Extends FileSystemInfo with file specific operations.
    • It is possible to create a FileInfo object for a non-existent file.
  • File
    • Contains static methods allowing you to perform operations without a FileInfo instance.
    • Most methods perform atomic operations when writing and reading files.

Examples

Encrypt File

FileInfo a = new FileInfo(@"\\davidcxp\Public\Hello.txt");
 
a.Encrypt();
// At this point, the file will be encrypted at NTFS level
// When you have colors enabled in Explorer, it'll be green.
 
a.Decrypt();

Replace & Backup File

FileInfo a = new FileInfo(@"C:\Public\Hello.txt");
 
// Moves Hello.txt to OtherHello.txt and backs up OtherHello.txt to BackupHello.txt
// Hello.txt and OtherHello.txt has to exist.
// Replace performs a call to ReplaceFile in kernel32.dll in the background
a.Replace(@"C:\Public\OtherHello.txt", @"C:\Public\BackupHello.txt");

Non-Existent File

FileInfo a = new FileInfo(@"C:\Public\bla.txt");
Console.WriteLine(a.Exists);

Writing Files

File.WriteAllText(@"C:\Public\Test.txt", "Hello");     // Overwrites Test.txt if it exists
File.AppendAllText(@"C:\Public\Test.txt", " There!");  // Appends or creates Text.txt