File reading basics
Great. We have written a file. Now we should be able to read it as well, right? Okay, let’s dive into that. We will start with a simple example: a file with some lines of text that we want to read into a string:
public string ReadFromFile(string fileName) { var text = File.ReadAllText(fileName); return text; }
I can’t make it simpler than this. We have the static ReadAllText
method, which takes a filename and reads all text into the string. Then we return that. Keep in mind that not all files contain text. I even dare to say that most files do not contain text. They are binary. Now, technically, a text
file is also a binary
file. So, let’s read the file again, but now by reading the actual bytes. I use the FileStream
this time, so we have a bit more control over what is happening:
public string ReadWithStream(string fileName) { byte[] fileContent; ...