Skip to main content

Writing to Files

In this tutorial, we'll cover how to write to files in C#. This is a crucial aspect of working with data, as you will often need to save information for use in future operations.

What is File I/O?

File I/O stands for File Input/Output. It is the process of reading from and writing data to files. In C#, the System.IO namespace provides classes to work with files and directories.

Writing to a File

To write to a file in C#, you can use the StreamWriter class. This class contains methods that allow you to write to a file asynchronously or synchronously.

Here's a basic example of how to write to a file:

using System.IO;

class Program
{
static void Main()
{
using (StreamWriter writer = new StreamWriter("test.txt"))
{
writer.WriteLine("Hello, World!");
}
}
}

In this example, we create a StreamWriter and use it to write the string "Hello, World!" to a file named "test.txt". If "test.txt" doesn't exist, it will be created. If it does exist, its contents will be overwritten.

Note the using statement. StreamWriter is an example of a disposable object, which means it uses resources that need to be cleaned up after use. The using statement ensures that this cleanup happens.

Appending to a File

If you want to add text to an existing file, you can do so by creating a StreamWriter with the append option set to true:

using System.IO;

class Program
{
static void Main()
{
using (StreamWriter writer = new StreamWriter("test.txt", true))
{
writer.WriteLine("Hello, again!");
}
}
}

In this example, the string "Hello, again!" is added to the end of "test.txt", rather than overwriting its existing contents.

Writing Multiple Lines

The StreamWriter class also allows you to write multiple lines to a file. You can do this by calling the WriteLine method multiple times:

using System.IO;

class Program
{
static void Main()
{
using (StreamWriter writer = new StreamWriter("test.txt"))
{
writer.WriteLine("Line 1");
writer.WriteLine("Line 2");
writer.WriteLine("Line 3");
}
}
}

This will write "Line 1", "Line 2", and "Line 3" on separate lines in "test.txt".

Writing Non-String Data

If you want to write non-string data to a file, you need to convert the data to a string first. You can do this with the ToString method:

using System.IO;

class Program
{
static void Main()
{
int number = 123;

using (StreamWriter writer = new StreamWriter("test.txt"))
{
writer.WriteLine(number.ToString());
}
}
}

In this example, we write the integer 123 to "test.txt" by converting it to a string.

In conclusion, writing to files in C# is a powerful tool that allows you to store data for future use. Whether you're writing strings, numbers, or more complex data, the StreamWriter class has the tools you need to get the job done. Happy coding!