File Class and FileInfo Class
Part of my 2008 study notes for exam 70-536 (.NET Framework 2.0).
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
You May Also Like
ArrayList Class
Resizeable, unordered, index-based collection. Suffers from boxing/unboxing when working with value types. Implements IEnumerator, allowing foreach…
BinaryReader Class and BinaryWriter Class
Used to read and write binary data from streams. Call the correct Read methods when using a BinaryReader.
BitArray Class
Contains an array of true/false values. Resizable through the Length property. Supports bitwise operations.



