c-sharp
  1. c-sharp-systemio

C# System.IO

The System.IO namespace provides classes for working with files, directories, and streams in C#. In this tutorial, we'll discuss how to use System.IO to perform common file operations such as reading and writing to files, creating and deleting directories, and working with streams.

Syntax

To use System.IO in C#, you first need to add the following namespace reference at the top of your code file:

using System.IO;

Then, you can use the classes provided by the System.IO namespace, such as File, Directory, and Stream.

using System.IO;

public class Example {
    public void FileExample() {
        // create a new file
        File.Create("myfile.txt");

        // write to a file
        string[] lines = {"Hello World", "From C#!"};
        File.WriteAllLines("myfile.txt", lines);

        // read from a file
        string[] readLines = File.ReadAllLines("myfile.txt");

        // delete a file
        File.Delete("myfile.txt");
    }
}

Example

The example code above creates a new file called "myfile.txt", writes two lines of text to the file, reads the lines from the file, and deletes the file.

Output

There is no output in the example above, but if you were to run the code, it would create, write to, read from, and delete a file called "myfile.txt".

Explanation

In the example above, we used the static methods provided by the System.IO.File class to create, write to, read from, and delete a file. We first created a new file by calling the File.Create method. Then, we wrote two lines of text to the file using the File.WriteAllLines method. Next, we read the lines from the file using the File.ReadAllLines method. Finally, we deleted the file using the File.Delete method.

Use

System.IO can be used for a wide range of file and stream related tasks in C#, such as reading and writing to files, creating directories, and working with streams. You can use System.IO to read and write text and binary files, as well as to perform backup and archive operations, and more.

Important Points

  • Always enclose file operations in a try-catch block to handle any exceptions that may occur.
  • Be aware that file and directory access requires appropriate file system permissions.
  • When working with streams, always make sure to release the resources by calling the Close method.

Summary

In this tutorial, we discussed how to use System.IO in C# to perform common file operations such as reading and writing to files, creating and deleting directories, and working with streams. We covered the syntax, example, output, explanation, use, important points, and summary of using System.IO in C#. With this knowledge, you can now work with files and streams in your C# applications.

Published on: