📅  最后修改于: 2023-12-03 14:39:44.086000             🧑  作者: Mango
StreamReader
and StreamWriter
are two classes in C# that allow us to read from and write to files, respectively. In this article, we will focus on how to use StreamReader
to read from a file.
To create a StreamReader
object, we need to pass the path of the file we want to read to the constructor of the StreamReader
class. Here's an example:
StreamReader reader = new StreamReader("path/to/file.txt");
This creates a StreamReader
object that reads from the file specified by the path. We can now use this object to read from the file.
To read from a file, we use the ReadLine()
method of the StreamReader
class. This method reads the next line from the file and returns it as a string. We can use a while
loop to read all the lines in the file:
string line;
while ((line = reader.ReadLine()) != null)
{
// Process the line
}
In this example, line
is a string variable that will hold the current line read from the file. The while
loop will continue to execute as long as ReadLine()
returns a non-null value, which means there are still lines to read from the file.
When we are finished reading from the file, we should close the StreamReader
object to free up resources. We can do this by calling the Close()
method:
reader.Close();
Alternatively, we can use a using
statement to automatically close the StreamReader
object when we are done with it:
using (StreamReader reader = new StreamReader("path/to/file.txt"))
{
string line;
while ((line = reader.ReadLine()) != null)
{
// Process the line
}
}
In this example, the StreamReader
object is automatically closed when the using
block is exited.
In this article, we learned how to use StreamReader
to read from a file in C#. We saw how to create a StreamReader
object, read lines from a file using ReadLine()
, and close the StreamReader
object when we are done with it.