Tutorial by Examples

You can use the System.IO.File.ReadAllText function to read the entire contents of a file into a string. string text = System.IO.File.ReadAllText(@"C:\MyFolder\MyTextFile.txt"); You can also read a file as an array of lines using the System.IO.File.ReadAllLines function: string[] line...
The System.IO.StreamWriter class: Implements a TextWriter for writing characters to a stream in a particular encoding. Using the WriteLine method, you can write content line-by-line to a file. Notice the use of the using keyword which makes sure the StreamWriter object is disposed as soon as ...
You can use the System.IO.File.WriteAllText function to write a string to a file. string text = "String that will be stored in the file"; System.IO.File.WriteAllText(@"C:\MyFolder\OutputFile.txt", text); You can also use the System.IO.File.WriteAllLines function which receiv...
When working with large files, you can use the System.IO.File.ReadLines method to read all lines from a file into an IEnumerable<string>. This is similar to System.IO.File.ReadAllLines, except that it doesn't load the whole file into memory at once, making it more efficient when working with l...
File static class By using Create method of the File static class we can create files. Method creates the file at the given path, at the same time it opens the file and gives us the FileStream of the file. Make sure you close the file after you are done with it. ex1: var fileStream1 = File.Create...
File static class File static class can be easily used for this purpose. File.Copy(@"sourcePath\abc.txt", @"destinationPath\abc.txt"); File.Copy(@"sourcePath\abc.txt", @"destinationPath\xyz.txt"); Remark: By this method, file is copied, meaning that it w...
File static class File static class can easily be used for this purpose. File.Move(@"sourcePath\abc.txt", @"destinationPath\xyz.txt"); Remark1: Only changes the index of the file (if the file is moved in the same volume). This operation does not take relative time to the fil...
string path = @"c:\path\to\file.txt"; File.Delete(path); While Delete does not throw exception if file doesn't exist, it will throw exception e.g. if specified path is invalid or caller does not have the required permissions. You should always wrap calls to Delete inside try-catch bloc...
Get all files in Directory var FileSearchRes = Directory.GetFiles(@Path, "*.*", SearchOption.AllDirectories); Returns an array of FileInfo, representing all the files in the specified directory. Get Files with specific extension var FileSearchRes = Directory.GetFiles(@Path, "*...
// filename is a string with the full path // true is to append using (System.IO.StreamWriter file = new System.IO.StreamWriter(filename, true)) { // Can write either a string or char array await file.WriteAsync(text); }

Page 1 of 1