Skip to main content

File Operations

Introduction

In C#, file operations are typically accomplished using the System.IO namespace, which provides classes and methods to perform various operations on files, such as creation, deletion, reading, writing, and more. In this tutorial, we will explore some of the most common file operations that you'll likely encounter when programming in C#.

Creating a File

To create a file in C#, you can use the File.Create() method from the System.IO namespace. Here's how to do it:

using System.IO;

class Program
{
static void Main()
{
File.Create("test.txt");
}
}

In this example, we created a file named test.txt in the same directory as the executable.

Writing to a File

Next, let's write some text to the file we just created. To do this, we'll use the File.WriteAllText() method. This method overwrites any existing data in the file.

using System.IO;

class Program
{
static void Main()
{
File.WriteAllText("test.txt", "Hello, world!");
}
}

In this example, we wrote the string "Hello, world!" to the file test.txt.

Reading from a File

Now, let's read the content we just wrote to the file. We can do this using the File.ReadAllText() method.

using System.IO;

class Program
{
static void Main()
{
string content = File.ReadAllText("test.txt");
Console.WriteLine(content);
}
}

When you run this code, it will output "Hello, world!".

Appending to a File

If you want to add more data to an existing file without deleting the current data, you can use the File.AppendAllText() method.

using System.IO;

class Program
{
static void Main()
{
File.AppendAllText("test.txt", " Welcome to C# File Operations.");
}
}

Now, if you read the content of the file again, it will output "Hello, world! Welcome to C# File Operations.".

Deleting a File

Finally, to delete a file, you can use the File.Delete() method.

using System.IO;

class Program
{
static void Main()
{
File.Delete("test.txt");
}
}

This will delete the file test.txt from the directory.

Summary

In this tutorial, we've learned how to create, write to, read from, append to, and delete a file in C# using the System.IO namespace. These are fundamental operations that you'll use often when dealing with files in your C# programs. Happy coding!