How to Use File.WriteAllText in C# to Write Text Files
Use
File.WriteAllText in C# to write a string directly to a file, creating the file if it doesn't exist or overwriting it if it does. You provide the file path and the text content as arguments, and the method handles the rest.Syntax
The File.WriteAllText method requires two main inputs: the file path and the text content you want to write. It writes the entire string to the file in one go.
- filePath: The location and name of the file to write.
- contents: The string data to write into the file.
This method overwrites the file if it already exists or creates a new one if it doesn't.
csharp
File.WriteAllText(string filePath, string contents);
Example
This example shows how to write a simple message to a text file named example.txt. If the file exists, it will be replaced with the new content.
csharp
using System; using System.IO; class Program { static void Main() { string path = "example.txt"; string text = "Hello, this is a test message!"; File.WriteAllText(path, text); Console.WriteLine("Text written to file successfully."); } }
Output
Text written to file successfully.
Common Pitfalls
Common mistakes when using File.WriteAllText include:
- Not having write permission to the file or folder, causing exceptions.
- Using an invalid file path or filename.
- Overwriting important files unintentionally because the method replaces existing content.
- Not handling exceptions that may occur during file writing.
Always ensure the path is correct and consider wrapping the call in a try-catch block to handle errors gracefully.
csharp
try { File.WriteAllText("C:\\invalid_path\\file.txt", "Sample text"); } catch (Exception ex) { Console.WriteLine($"Error writing file: {ex.Message}"); }
Quick Reference
| Parameter | Description |
|---|---|
| filePath | String path to the file to write. |
| contents | String text content to write into the file. |
| Behavior | Creates file if missing, overwrites if exists. |
| Exceptions | Throws IOException, UnauthorizedAccessException if issues occur. |
Key Takeaways
File.WriteAllText writes a full string to a file, replacing existing content.
Provide a valid file path and the text you want to save.
The method creates the file if it doesn't exist.
Be careful to avoid overwriting important files unintentionally.
Use try-catch to handle possible errors like permission issues.