File Handling in C
File handling is a crucial aspect of any programming language, as it allows you to read from and write to files on your computer. In C#, you can utilize the System.IO
namespace to perform file handling operations.
To create a file and write content to it, you can use the File.WriteAllText()
method. For example, let's create a file named example.txt
and write the text Hello, World!
to it:
1File.WriteAllText("./example.txt", "Hello, World!");
To read the entire content of a file, you can use the File.ReadAllText()
method. This method returns the contents of the specified file as a string. For example, let's read the content of example.txt
and print it to the console:
1string content = File.ReadAllText("./example.txt");
2Console.WriteLine(content);
If you want to append content to an existing file, you can use the File.AppendAllText()
method. This method appends the specified string to the file.
Let's append the text Goodbye, World!
to the example.txt
file:
1File.AppendAllText("./example.txt", "\nGoodbye, World!");
Finally, let's read the updated content of example.txt
and print it to the console:
1content = File.ReadAllText("./example.txt");
2Console.WriteLine(content);
File handling in C# allows you to store and retrieve data from files, which is vital for many real-world applications. Whether you need to read configuration files, log data, or process large input files, understanding file handling is an essential skill in C# programming.
xxxxxxxxxx
using System;
using System.IO;
class Program
{
static void Main()
{
// Creating a file
File.WriteAllText("./example.txt", "Hello, World!");
// Reading from a file
string content = File.ReadAllText("./example.txt");
Console.WriteLine(content);
// Appending to a file
File.AppendAllText("./example.txt", "\nGoodbye, World!");
content = File.ReadAllText("./example.txt");
Console.WriteLine(content);
}
}