Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# Program to Create File and Write to the File
Creating files and writing data to them is a fundamental aspect of file handling in C#. The System.IO namespace provides several methods to create and write to files efficiently. This article covers various approaches to create files and write content using different methods.
File handling operations rely on streams, which provide a generic view of a sequence of bytes. Streams serve as the gateway between your application and file operations, enabling input and output processes.
Using File.WriteAllText() Method
The File.WriteAllText() method is one of the simplest ways to create a file and write text content. It creates a file with the specified name and writes string data to it. If the file already exists, it overwrites the existing content.
Syntax
public static void WriteAllText(string path, string contents);
This method uses UTF-8 encoding by default without a Byte-Order Mark (BOM). An optional encoding parameter can be specified if needed.
Example
using System;
using System.IO;
class FileWriteExample {
public static void Main() {
string filePath = "tutpoint.txt";
string content = "Welcome to Tutorials Point - Your learning destination!";
File.WriteAllText(filePath, content);
Console.WriteLine("File created and text written successfully.");
Console.WriteLine("Content: " + File.ReadAllText(filePath));
}
}
The output of the above code is
File created and text written successfully. Content: Welcome to Tutorials Point - Your learning destination!
Using File.WriteAllLines() Method
The File.WriteAllLines() method creates a file and writes multiple lines of text from a string array. Each array element becomes a separate line in the file.
Syntax
public static void WriteAllLines(string path, string[] contents);
Example
using System;
using System.IO;
class FileWriteLinesExample {
public static void Main() {
string filePath = "courses.txt";
string[] courses = {
"C# Programming",
"Java Development",
"Python Basics",
"Web Development"
};
File.WriteAllLines(filePath, courses);
Console.WriteLine("File created with multiple lines.");
Console.WriteLine("File contents:");
string[] readLines = File.ReadAllLines(filePath);
foreach(string line in readLines) {
Console.WriteLine("- " + line);
}
}
}
The output of the above code is
File created with multiple lines. File contents: - C# Programming - Java Development - Python Basics - Web Development
Using File.WriteAllBytes() Method
The File.WriteAllBytes() method writes binary data from a byte array to a file. This is useful when working with binary content or when you need precise control over encoding.
Syntax
public static void WriteAllBytes(string path, byte[] bytes);
Example
using System;
using System.IO;
using System.Text;
class FileBytesExample {
public static void Main() {
string filePath = "binary_data.txt";
string message = "Learning C# file handling with bytes!";
byte[] dataBytes = Encoding.UTF8.GetBytes(message);
File.WriteAllBytes(filePath, dataBytes);
Console.WriteLine("Binary data written to file.");
Console.WriteLine("File size: " + new FileInfo(filePath).Length + " bytes");
// Read back the data
byte[] readBytes = File.ReadAllBytes(filePath);
string retrievedText = Encoding.UTF8.GetString(readBytes);
Console.WriteLine("Retrieved content: " + retrievedText);
}
}
The output of the above code is
Binary data written to file. File size: 37 bytes Retrieved content: Learning C# file handling with bytes!
Using Asynchronous File Operations
For non-blocking file operations, C# provides asynchronous methods. The File.WriteAllTextAsync() method allows writing files asynchronously, preventing UI freezing in applications.
Syntax
public static Task WriteAllTextAsync(string path, string contents, CancellationToken cancellationToken = default);
Example
using System;
using System.IO;
using System.Threading.Tasks;
class AsyncFileExample {
public static async Task Main() {
string filePath = "async_file.txt";
string content = "Asynchronous file writing in C#";
Console.WriteLine("Starting async file write...");
await File.WriteAllTextAsync(filePath, content);
Console.WriteLine("Async file write completed.");
// Verify the file was created
if (File.Exists(filePath)) {
string readContent = await File.ReadAllTextAsync(filePath);
Console.WriteLine("File content: " + readContent);
}
}
}
The output of the above code is
Starting async file write... Async file write completed. File content: Asynchronous file writing in C#
Comparison of File Writing Methods
| Method | Input Type | Use Case | Encoding |
|---|---|---|---|
| WriteAllText() | Single string | Simple text content | UTF-8 default |
| WriteAllLines() | String array | Multiple lines of text | UTF-8 default |
| WriteAllBytes() | Byte array | Binary data or custom encoding | User-controlled |
| WriteAllTextAsync() | Single string | Non-blocking operations | UTF-8 default |
Conclusion
C# provides multiple methods to create files and write content, each suited for different scenarios. Use WriteAllText() for simple string content, WriteAllLines() for multiple lines, WriteAllBytes() for binary data, and async methods for non-blocking operations. Choose the appropriate method based on your data type and performance requirements.
