📜  c# streamreader to file - C# (1)

📅  最后修改于: 2023-12-03 14:39:44.086000             🧑  作者: Mango

C# StreamReader to File

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.

Creating a StreamReader Object

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.

Reading from a 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.

Closing the StreamReader Object

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.

Summary

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.