ZetCode

C# File

last modified January 15, 2024

In this article we show how to work with files in C#. We create files, read files, delete files, write to files, and append to files.

To work with files in C#, we use the System.IO and System.Text namespaces.

The File class of the System.IO provides static methods for the creation, copying, deletion, moving, and opening of a single file. It also helps in the creation of FileStream objects.

There is a similar FileInfo in .NET. While FileInfo is an instance of a file representing the file, File is a utility class for working with any file.

The words.txt file

This is a text file that we work with in some examples.

words.txt
sky
blue
cloud
raisin
tree
falcon
owl
eagle
rock
water
lake

C# File.Create

The File.create creates or overwrites a file in the specified path. It returns a FileStream, which provides read/write access to the file specified in path.

Program.cs
using System.Text;

var path = "words.txt";

using FileStream fs = File.Create(path);
byte[] data = Encoding.UTF8.GetBytes("falcon\nribbon\ncloud");
fs.Write(data, 0, data.Length);

Console.WriteLine("data written to file");

The example creates a file and writes three words into it.

using FileStream fs = File.Create(path);

We create a file and retrieve a file stream to the file.

byte[] data = Encoding.UTF8.GetBytes("falcon\nribbon\ncloud");

We get the bytes of the three words we are going to write with Encoding.UTF8.GetBytes.

fs.Write(data, 0, data.Length);

The bytes are written to the file with Write.

C# File.CreateText

The File.CreateText creates or opens a file for writing UTF-8 encoded text. If the file already exists, its contents are overwritten. It returns a StreamWriter that writes to the specified file using UTF-8 encoding.

Program.cs
var path = "words.txt";

using StreamWriter sw = File.CreateText(path);

sw.WriteLine("falcon");
sw.WriteLine("sky");
sw.WriteLine("cloud");

Console.WriteLine("data written to file");

The example creates a new file with File.CreateText. It writes three words with WriteLine.

C# File.Copy

The File.copy copies an existing file to a new file. It takes the source file and the destination file as parameters.

Program.cs
var sourcePath = "words.txt";
var destPath = "words_bck.txt";

File.Copy(sourcePath, destPath);

Console.WriteLine("file copied");

The example copies a text file.

C# File.Move

The File.Move moves a specified file to a new location. With this method, we can move a file to a new location or to rename a file.

Program.cs
var sourcePath = "words.txt";
var destPath = "data.txt";

File.Move(sourcePath, destPath);

Console.WriteLine("file moved");

The example renames words.txt to data.txt.

C# File.Exists

The File.Exists determines whether the specified file exists.

Program.cs
var path = "words2.txt";

if (File.Exists(path))
{
    Console.WriteLine("the file exists");
} else {

    Console.WriteLine("the file does not exist");
}

In the code example we check if the words2.txt file exists.

C# File.Delete

The File.Delete deletes the specified file.

Program.cs
var path = "words.txt";

File.Delete(path);

Console.WriteLine("file deleted");

The example deletes a text file.

C# File.GetCreationTime

The File.GetCreationTime returns the creation date and time of the specified file or directory.

Program.cs
var path = "words.txt";

DateTime dt = File.GetCreationTime(path);

Console.WriteLine($"Creation time: {dt}");

The example prints the creation time of the words.txt file.

$ dotnet run
Creation time: 16. 1. 2024 11:31:35

C# File.GetLastWriteTime

The File.GetLastWriteTime returns the date and time of the specified file or directory was last written to.

Program.cs
var path = "words.txt";

DateTime dt = File.GetLastWriteTime(path);

Console.WriteLine($"Last write time: {dt}");

The example prints the last write time of the text file.

C# File.Open

The File.Open opens a FileStream on the specified path. The overloaded methods of File.Open allow to specify the file mode (Open, Create, CreateNew, Truncate, Append, or OpenOrCreate), the file access (Read, Write, ReadWrite).

The file share value specifies the type of access other threads have to the file, such as Delete, None, Read, ReadWrite, Write, or Inheritable.

Program.cs
using System.Text;

var path = "words.txt";

using FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read);

byte[] buf = new byte[1024];
int c;

while ((c = fs.Read(buf, 0, buf.Length)) > 0)
{
    Console.WriteLine(Encoding.UTF8.GetString(buf, 0, c));
}

The example reads the contents of the words.txt file.

using FileStream fs = File.Open(path, FileMode.Open, FileAccess.Read);

We open the file for reading.

byte[] buf = new byte[1024];
int c;

We create a buffer of bytes and an auxiliary variable.

while ((c = fs.Read(buf, 0, buf.Length)) > 0)
{
    Console.WriteLine(Encoding.UTF8.GetString(buf, 0, c));
}

The Read method reads a block of bytes from the stream and writes the data to the given buffer. The Encoding.UTF8.GetString decodes a sequence of bytes into a string.

$ dotnet run
sky
blue
cloud
raisin
tree
falcon
owl
eagle
rock
water
lake

C# File.OpenRead

The File.OpenRead opens an existing file for reading. It returns a read-only FileStream on the specified path. It is a convenience method to the File.Open.

Program.cs
using System.Text;

var path = "words.txt";

using FileStream fs = File.OpenRead(path);

byte[] buf = new byte[1024];
int c;

while ((c = fs.Read(buf, 0, buf.Length)) > 0)
{
    Console.WriteLine(Encoding.UTF8.GetString(buf, 0, c));
}

The example reads a file with File.OpenRead.

C# File.OpenText

The File.OpenText opens an existing UTF-8 encoded text file for reading. It returns a StreamReader on the specified path.

Program.cs
var path = "words.txt";

using StreamReader sr = File.OpenText(path);

string s = String.Empty;

while ((s = sr.ReadLine()) != null)
{
    Console.WriteLine(s);
}

The example opens a text file and reads its contents.

while ((s = sr.ReadLine()) != null)
{
    Console.WriteLine(s);
}

We read the text file line by line. We do not have to decode the bytes into the string ourselves.

C# File.OpenWrite

The File.OpenWrite opens an existing file or creates a new file for writing. It returns a FileStream object on the specified path with write access.

Program.cs
var path = "langs.txt";

using FileStream fs = File.OpenWrite(path);
using StreamWriter sr = new StreamWriter(fs);

sr.WriteLine("PHP\nDart\nJava\nC#\n");

Console.WriteLine("data written");

The example opens a file in write mode and writes a line to the file.

using FileStream fs = File.OpenWrite(path);
using StreamWriter sr = new StreamWriter(fs);

We open a filestream to the specified path. The stream is passed to the StreamWriter, which is used to write characters in a particular encoding (UTF8 by default).

sr.WriteLine("PHP\nDart\nJava\nC#\n");

A line of text is written to the file with WriteLine.

C# File.ReadLines

The File.ReadLines opens a text file, reads all lines of the file into a string array, and then closes the file.

Program.cs
var path = "words.txt";

var lines = File.ReadLines(path);

foreach (var line in lines)
{
    Console.WriteLine(line);
}

The example reads all lines of a text file. The returned array of strings is traversed with a foreach loop.

C# File.ReadAllText

The File.ReadAllText opens a text file, reads all the text in the file into a string, and then closes the file. Note that this method should not be used for very large files.

Program.cs
var path = "words.txt";

string readText = File.ReadAllText(path);
Console.WriteLine(readText);

The example reads the whole text into a string in one go.

C# File.ReadAllBytes

The File.ReadAllBytes opens a binary file, reads the contents of the file into a byte array, and then closes the file.

Program.cs
var path = "favicon.ico";
byte[] data = File.ReadAllBytes(path);

int i = 0;

foreach (byte c in data)
{
    Console.Write("{0:X2} ", c);
    i++;

    if (i % 10 == 0)
    {
        Console.WriteLine();
    }
}

The example reads a favicon.ico binary file. The data is printed to the console in hex format.

$ dotnet run
00 00 01 00 01 00 10 10 00 00
00 00 00 00 68 05 00 00 16 00
00 00 28 00 00 00 10 00 00 00
20 00 00 00 01 00 08 00 00 00
00 00 00 01 00 00 00 00 00 00
00 00 00 00 00 01 00 00 00 00
00 00 00 00 00 00 FF FF FF 00
4D 45 3D 00 00 00 00 00 00 00
...

C# File.WriteAllText

The File.WriteAllText creates a new file, writes the contents to the file, and then closes the file. If the target file already exists, it is overwritten.

Program.cs
var path = "words.txt";

string data = "sky\ncloud\nfalcon\nowl\ncrane";
File.WriteAllText(path, data);

Console.WriteLine("data written");

In the example, we write four words to a file with File.WriteAllText.

C# File.WriteAllLines

The File.WriteAllLines creates a new file, writes one or more strings to the file, and then closes the file.

Program.cs
using System.Text;

var path = "words.txt";

string[] data = { "sky", "cloud", "falcon", "hawk" };
File.WriteAllLines(path, data, Encoding.UTF8);

Console.WriteLine("data written");

In the example, we have an array of strings. We write these strings to a file in one go with File.WriteAllLines.

C# File.WriteAllBytes

The File.WriteAllBytes creates a new file, writes the specified byte array to the file, and then closes the file.

Program.cs
using System.Text;

var path = "words.txt";

var text = "falcon\nhawk\nforest\ncloud\nsky";
byte[] data = Encoding.UTF8.GetBytes(text);

File.WriteAllBytes(path, data);

Console.WriteLine("data written");

The example writes data to a file with File.WriteAllBytes.

var text = "falcon\nhawk\nforest\ncloud\nsky";
byte[] data = Encoding.UTF8.GetBytes(text);

First, we transform the text data into a array of bytes with Encoding.UTF8.GetBytes.

File.WriteAllBytes(path, data);

Then we write the array to the file with File.WriteAllBytes.

C# File.AppendText

The File.AppendText creates a StreamWriter that appends UTF-8 encoded text to an existing file, or to a new file if the specified file does not exist.

Program.cs
var path = "words.txt";

using StreamWriter sw = File.AppendText(path);

sw.WriteLine("sky");
sw.WriteLine("lake");

The example appends two words to the words.txt file.

C# File.AppendAllText

The File.AppendAllText appends the specified string to the file. It creates the file if it does not exist.

Program.cs
var path = "words.txt";
var contents = "armour\nsword\narrow\n";

File.AppendAllText(path, contents);

Console.WriteLine("text appended to file");

The example appends three words to the specified text file.

C# File.AppendAllLines

The File.AppendAllLines appends lines to a file, and then closes the file.

Program.cs
var path = "words.txt";
List<string> data = ["brown", "blue", "khaki"];

File.AppendAllLines(path, data);

Console.WriteLine("data written to file");

The example appends a list of strings to the file with File.AppendAllLines.

In this article we have worked with files in C#. We have utilized the File class of the System.IO.

Source

C# File class - language reference

Author

My name is Jan Bodnar and I am a passionate programmer with many years of programming experience. I have been writing programming articles since 2007. So far, I have written over 1400 articles and 8 e-books. I have over eight years of experience in teaching programming.

List all C# tutorials.