C# file io

In C#, file I/O (Input/Output) operations are performed using the System.IO namespace. This namespace provides classes for working with files, directories, and streams. Here are some of the most commonly used classes and methods for performing file I/O operations in C#:

  1. File class: This class provides static methods for creating, deleting, copying, and moving files, as well as methods for reading from and writing to files.
// Create a file
File.Create("file.txt");

// Write to a file
File.WriteAllText("file.txt", "Hello, world!");

// Read from a file
string contents = File.ReadAllText("file.txt");

// Delete a file
File.Delete("file.txt");
Sourc‮.www:e‬theitroad.com
  1. Directory class: This class provides static methods for creating, deleting, and enumerating directories.
// Create a directory
Directory.CreateDirectory("directory");

// Get the files in a directory
string[] files = Directory.GetFiles("directory");

// Delete a directory
Directory.Delete("directory");
  1. StreamReader and StreamWriter classes: These classes provide methods for reading from and writing to streams, including files.
// Write to a file using StreamWriter
using (StreamWriter writer = new StreamWriter("file.txt"))
{
    writer.WriteLine("Hello, world!");
}

// Read from a file using StreamReader
using (StreamReader reader = new StreamReader("file.txt"))
{
    string contents = reader.ReadToEnd();
}

It is important to note that when working with files, you should always close the file when you are finished with it, either by calling the Close() method or by using the using statement as shown in the above examples. This ensures that the file is properly closed and any resources associated with it are released.

C# also provides additional classes for working with streams, such as FileStream, MemoryStream, and NetworkStream. These classes can be used to read from and write to files, in-memory data, and network connections, respectively.