Brief intro to the File API in .NET

.NET has a good, high-level File API that abstracts away the complexity of file operations. You can create, read, update, delete, and search for files with a single method call in most scenarios. The File API is located in the System.IO namespace.

Here’s a brief example of creating a new file with content, reading its content, updating it, and then deleting it:

using System.IO;

var filePath = @"C:\temp\hello.txt";

//Create a new file with content
File.WriteAllText(filePath, "Hello");

//Read a file's content
var text = File.ReadAllText(filePath);
Console.WriteLine($"File contains: {text}");

//Update a file (by appending to the end)
File.AppendAllText(filePath, " World");
Console.WriteLine($"Updated file contains: {File.ReadAllText(filePath)}");

//Delete a file
Console.WriteLine($"File exists? {File.Exists(filePath)}");
Code language: C# (cs)

This outputs the following:

File contains: Hello
Updated file contains: Hello World
File exists? FalseCode language: plaintext (plaintext)

As you can see, many file IO tasks can be accomplished by calling a single method. That’s great for productivity.

The File API is flexible and provides multiple approaches solving problems, which means you can pick the best tool for the job. For example, you can load an entire file all at once, or stream it into memory line-by-line. In most cases, you can even choose between synchronous and asynchronous methods.

This was just a brief overview. Check out our other how-to articles about files and directories:

Leave a Comment