Last active
October 26, 2019 02:42
-
-
Save joe-oli/75cd0011bcf15ba3a53d8d8a325167f5 to your computer and use it in GitHub Desktop.
Files, streams, etc
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//1.) for small files only, load all contents into memory | |
string content = File.ReadAllText("path/to/TextFile.txt", Encoding.UTF8); | |
//2.) ...or read lines into an array | |
string[] linesArr = File.ReadAllLines("path/to/TextFile.txt", Encoding.UTF8); | |
foreach (string line in linesArr) { | |
//do stuff with each line. | |
} | |
//3.) ... or open a stream for reading (StreamReader) | |
string content = String.Empty; | |
FileStream fs = new FileStream("path/to/TextFile.txt", FileMode.Open, FileAccess.Read); | |
using (StreamReader streamReader = new StreamReader(fs, Encoding.UTF8)) | |
{ | |
content = streamReader.ReadToEnd(); | |
} | |
//4.) For larger files, read line by line | |
FileStream fs = new FileStream("path/to/TextFile.txt", FileMode.Open, FileAccess.Read); | |
using (StreamReader streamReader = new StreamReader(fs, Encoding.UTF8)) | |
{ | |
string line = String.Empty; | |
while ( (line = streamReader.ReadLine() ) != null) | |
{ | |
//do stuff with line... | |
} | |
} | |
//5.) READ Async example | |
static async void ReadFileAsync() { | |
FileStream fs = new FileStream("path/to/TextFile.txt", FileMode.Open, FileAccess.Read); | |
using (StreamReader reader = new StreamReader(fs, Encoding.UTF8)) | |
{ | |
string content = await reader.ReadToEndAsync(); | |
//internal to this FN, control exits in the above line to the caller.. (i.e. the method execution is suspended)... and continues below once all contents read | |
//... file read finished, do stuff with content | |
} | |
} | |
//5.b) USAGE | |
Task t = new Task(ReadFileAsync); | |
t.Start(); //start reading... (async, does NOT block/wait until reading is finished) | |
//next statement immediately; | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment