Conteúdo do Curso
C# Beyond Basics
C# Beyond Basics
Reading Files using StreamReader
We can open and read files using the C# programming language.
For reading a file, we create a new StreamReader
object. The StreamReader
object takes in the path of the file.
index
Here fileVarName
represents the variable name in which we will store the StreamReader object, and fullPath
is supposed to be the full path of the file in the form of a string.
For-example we want to open a file "text.txt" on Desktop which has the path C:/Users/Admin/Desktop/text.txt
:
index
Consider the text.txt
file has the following content:
text
A StreamReader
object has a ReadLine
method which reads one line from the file and returns it:
index
Output:
The ReadLine
method automatically switches the cursor to the next line so when it's called again, it reads the next line if there is any, otherwise it simply returns null
(nothing):
index
Output:
For reading all the lines from a file we can use the while
loop with a condition which checks if the next line is null
or not. Following is a simple way we can do that:
index
Output:
We can make the above code a bit neater using a trick, for that lets take a look at the assignment statements. An assignment statement has a return value as well, which is the value that is being assigned. It can be understood with an example:
index
Output:
It outputs 7
because the statement a = 7
returns 7
which is the value being assigned to a
.
We can use this information to do some creative things like assigning the same value to multiple variables in a single statement:
index
Output:
Using this information, we can modify the file reading code to make it shorter removing unnecessary code:
index
Inside the condition we first used an assignment statement line = textFile.ReadLine()
which automatically updates the line
variable and then checks if it's null from the statement's return value.
After reading the file we must also close it using the Close
method, otherwise it can potentially cause memory leaks or the file can be locked and become inaccessible from other places as long as the program is running.
The final code will look something like this:
index
Tudo estava claro?