Read the syntax
File provides convenience methods for small text files. Specify encoding explicitly and clean up temporary files even when an operation throws. Use a .NET 8+ console project; replace Program.cs with this C# example.
GetTempFileName creates a temporary file. The finally block removes that exact file after the read, including when writing or reading fails.
Syntax
File.WriteAllText(path, text, Encoding.UTF8); File.ReadAllText(path, Encoding.UTF8)Examples
Text Files and Cleanup
Use a .NET 8+ console project; replace Program.cs with this C# example.
using System;
using System.IO;
using System.Text;
string path = Path.GetTempFileName();
try
{
File.WriteAllText(path, "Hello, Ada", Encoding.UTF8);
Console.WriteLine(File.ReadAllText(path, Encoding.UTF8));
}
finally
{
File.Delete(path);
}- Expected output: Hello, Ada
- GetTempFileName creates a temporary file. The finally block removes that exact file after the read, including when writing or reading fails.
- Use streaming APIs for large files rather than loading all content at once.
Best practices
- Use streaming APIs for large files rather than loading all content at once.
- Handle IOException and UnauthorizedAccessException where the application can provide a meaningful recovery.
Runtime & versions
.NET runtime. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
C# language reference