Mark As Completed Discussion

File Input and Output

File input and output is a fundamental topic in programming, allowing you to read and write data to files. In C#, you can use the StreamReader and StreamWriter classes from the System.IO namespace to perform file input and output operations.

Writing to a File

To write data to a file, you can use the StreamWriter class. First, specify the filepath where you want to create or overwrite the file. Then, use the StreamWriter to write data to the file. Here's an example:

TEXT/X-CSHARP
1string filePath = "data.txt";
2
3// Writing to a file
4using (StreamWriter writer = new StreamWriter(filePath))
5{
6    writer.WriteLine("Hello, World!");
7    writer.WriteLine("This is a test file.");
8}

In this example, we create a StreamWriter object and pass the filepath to the constructor. We can then use the WriteLine method to write lines of text to the file.

Reading from a File

To read data from a file, you can use the StreamReader class. First, specify the filepath of the file you want to read from. Then, use the StreamReader to read data from the file. Here's an example:

TEXT/X-CSHARP
1string filePath = "data.txt";
2
3// Reading from a file
4using (StreamReader reader = new StreamReader(filePath))
5{
6    string line;
7    while ((line = reader.ReadLine()) != null)
8    {
9        Console.WriteLine(line);
10    }
11}

In this example, we create a StreamReader object and pass the filepath to the constructor. We can then use the ReadLine method to read each line of the file and print it to the console.

File input and output is a powerful tool that allows you to store and retrieve data from external files, making your programs more flexible and versatile.

C#
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment