Lazily reading a file line-by-line via an IEnumerable
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 large files.
The second parameter of File.ReadLines is optional. You may use it when it is required to specify encoding.
It is important to note that calling ToArray, ToList or another similar function will force all of the lines to be loaded at once, meaning that the benefit of using ReadLines is nullified. It is best to enumerate over the IEnumerable using a foreach loop or LINQ if using this method.
Writing lines to a file using 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 it goes out of scope and thus the file is closed.
string[] lines ={"My first string","My second string","and even a third string"};using(System.IO.StreamWriter sw =newSystem.IO.StreamWriter(@"C:\MyFolder\OutputText.txt")){foreach(string line in lines){
sw.WriteLine(line);}}
Note that the StreamWriter can receive a second bool parameter in it's constructor, allowing to Append to a file instead of overwriting the file:
bool appendExistingFile =true;using(System.IO.StreamWriter sw =newSystem.IO.StreamWriter(@"C:\MyFolder\OutputText.txt", appendExistingFile )){
sw.WriteLine("This line will be appended to the existing 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(opens new window) function which receives an IEnumerable<String> as the second parameter (as opposed to a single string in the previous example). This lets you write content from an array of lines.
string[] lines ={"My first string","My second string","and even a third string"};
System.IO.File.WriteAllLines(@"C:\MyFolder\OutputFile.txt", lines);
Copy File
File static class
File static class can be easily used for this purpose.
Remark: By this method, file is copied, meaning that it will be read from the source and then written to the destination path. This is a resource consuming process, it would take relative time to the file size, and can cause your program to freeze if you don't utilize threads.
Async write text to a file using StreamWriter
// filename is a string with the full path// true is to append using(System.IO.StreamWriter file =newSystem.IO.StreamWriter(filename,true)){// Can write either a string or char arrayawait file.WriteAsync(text);}
Create File
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("samplePath");/// you can write to the fileStream1
fileStream1.Close();
ex2:
using(var fileStream1 = File.Create("samplePath")){/// you can write to the fileStream1}
ex3:
File.Create("samplePath").Close();
FileStream class
There are many overloads of this classes constructor which is actually well documented here(opens new window). Below example is for the one that covers most used functionalities of this class.
var fileStream2 =newFileStream("samplePath", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
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 block(opens new window) and handle all expected exceptions. In case of possible race conditions, wrap logic inside lock statement(opens new window).
Files and Directories
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, "*.pdf", SearchOption.AllDirectories);
Returns an array of FileInfo, representing all the files in the specified directory with the specified extension.
Syntax
new System.IO.StreamWriter(string path)
new System.IO.StreamWriter(string path, bool append)