While trying to copy, move, rename, create, open, delete and appending to files we use File and FileInfo classes. File and File info classes derive from System.IO namespace. File class provides us static methods to work with files and FileInfo provides us with instance methods. Generally, you will use File class when working with a file and perform one operation on it. Difference between File and FileInfo approaches is that FileInfo does security checking only once (while accessing files). Because FileInfo is a instance method it does not tack changes to a file so you will have to take a lot of precautions while using that class. File class is on a disadvantage, because you always have to apply path to a file, meaning, it takes more parameters than FileInfo class. Try discovering yourself which approach is faster in your scenario. Also both classes help us while creating FileStream (to be explained in next post).
Common operations working with File class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 |
class App { private static void Main() { // Before we start path to desired file // must be created and stored as a string string path = @"D:\csharp\test.txt"; // Path can also be in following formats // c:\\csharp\\test.txt // \\\\MyServer\\MyFolder // We are checking if file in provided location exists // If file does not exist we will create it // In case that folder we provided does not exist // DirectoryNotFoundException will be thrown if (!File.Exists(path)) File.Create(path); // File.ReadAllLines returns string array // so we can iterate through array and display or use values string[] allLinesFromFile = File.ReadAllLines(path); foreach (var line in allLinesFromFile) { Console.WriteLine(line); } // We can see when file was created DateTime fileCreatedDate = File.GetCreationTime(path); // Change date of creation DateTime newCreatedDate = new DateTime(2016,05,20); File.SetCreationTime(path, newCreatedDate); // Lines are added to a file by using AppendAllLines method // AppendAllLines requires path to a file // and collection that implements IEnumerable List<string> linesToBeAppended = new List<string>(); linesToBeAppended.Add("First additional line."); linesToBeAppended.Add("Last additional line."); File.AppendAllLines(path, linesToBeAppended); // WriteAllBytes method deletes file if it allready exists, // creates a new file and adds array of bytes to a file byte[] byteArray = new byte[] { 0x21, 0x22, 0x23, 0x24 }; File.WriteAllBytes(path, byteArray); // WriteAllText method deletes file if it already exists, // creates a new file and adds one line at the beginning of a file File.WriteAllText(path, "New line in a new file."); // WriteAllLines method deletes file if it already exists, // creates a new file and adds collection of strings to a file File.WriteAllLines(path, linesToBeAppended); // Reads entire Txt file // and returns it as an byte array byte[] readBytes = File.ReadAllBytes(path); // Reads entire Txt file // and returns it as an string array string[] readLines = File.ReadAllLines(path); // Reads entire Txt file // and returns it as a single string string readTxt = File.ReadAllText(path); // In contrast to ReadAllLines, // ReadLines uses an enumerator to read each line. // Meaning it will not read entire file and return us // all the values but will read lines until we tell it // to stop or until it goes through entire file. ReadLines(path); // Delete method deletes file in provided path File.Delete(path); } private static bool ReadLines(string path) { foreach (var line in File.ReadLines(path)) { if (line == "Last additional line.") return true; Console.WriteLine(line); } return false; } } |
Common operations working with FileInfo class
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
using System; using System.Collections.Generic; using System.IO; namespace FileInfoApplication { class Program { static void Main(string[] args) { // Before we start path to desired file // must be created and stored as a string string filePath = @"D:\csharp\test.txt"; // Path can also be in following formats // c:\\csharp\\test.txt // \\\\MyServer\\MyFolder // Because File info is not a static class // we need to create an instance of FileInfo class // with provided path to a file FileInfo file = new FileInfo(filePath); //We are checking if file in provided location exists //If file does not exist we will create it // In case that folder we provided does not exist // DirectoryNotFoundException will be thrown if (!file.Exists) using (FileStream tt = file.Create()) { } // File.ReadAllLines returns string array // so we can iterate through array and display or use values string[] allLinesFromFile = File.ReadAllLines(filePath); foreach (var line in allLinesFromFile) { Console.WriteLine(line); } // We can see when file was created DateTime fileCreatedDate = file.CreationTime; Console.WriteLine("File was created on : {0}", fileCreatedDate.ToShortDateString()); // Lines are added to the end of a file // by using StreamWriter class // and FileInfo.AppendText method List<string> linesToBeAppended = new List<string> { "First appended line from a List of strings.", "Last appended line from a List of strings." }; using (StreamWriter sw = file.AppendText()) { foreach (var line in linesToBeAppended) { sw.WriteLine(line); } sw.WriteLine("Single appended line."); } // A line is added to the start of a file // by using StreamWriter // and FileInfo.CreateText method // If file exist before CreateText method // deletes it and creates a new file using (StreamWriter sw = file.CreateText()) { sw.WriteLine("Single appended line to the beginning of a file."); } // By using a BinaryWriter we can use FileInfo instance // to write an array of bytes to a file byte[] byteArray = new byte[] { 0x21, 0x22, 0x23, 0x24 }; using (BinaryWriter bw = new BinaryWriter(file.Open(FileMode.Create))) { for (int i = 0; i < byteArray.Length; i++) { bw.Write(i); } } // Reads entire Txt file and returns bytes List<byte> byteList = new List<byte>(); using (BinaryReader br = new BinaryReader(file.Open(FileMode.Open))) { byte value = 0; while (br.BaseStream.Position < br.BaseStream.Length) { value = br.ReadByte(); byteList.Add(value); } } // Reads entire Txt file // and returns it as an string array List<string> listOfStrings = new List<string>(); using (StreamReader lines = file.OpenText()) { string line = ""; while ((line = lines.ReadLine()) != null) { listOfStrings.Add(line); } } // CopyTo method copies file to another location const string filePath2 = @"D:\csharp\test2.txt"; file.CopyTo(filePath2); // MoveTo mehod copies file to another location // and deletes file from current location const string filePath3 = @"D:\csharp\test3.txt"; FileInfo file2 = new FileInfo(filePath2); file2.MoveTo(filePath3); //// Delete method deletes file in provided path FileInfo file3 = new FileInfo(filePath3); file3.Delete(); } } } |
I hope you had no problem with learning how to use File and FileInfo classes. If you found File and FileInfo classes interesting I recommend that you continue learning about Streams.