Tuesday, June 16, 2026

C# Creating file and Writing into the file in different ways

In all these examples, file is created inside My Document folder. We learn fundamental approaches to create a new file and write some text into the file. We can also create image file using the same way but we should rely on BinaryWriter for this. In following examples, File.Create and File.CreateText static methods are used to create a file.

Technique1. Create a new File and Close it explicitly
var mydocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string filepath = Path.Combine(mydocs, "create.txt");
// if file exists, no error is thrown, overwrite old one
File.Create(filepath).Close();
Technique2. Create a new File and Close its stream explicitly
var mydocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string filepath = Path.Combine(mydocs, "create.txt");
// if file exists, no error is thrown, overwrite old one
FileStream fileStream = File.Create(filepath);
fileStream.Close();
Technique3. Create a new File and Close it implicitly by 'using' expression
var mydocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string filepath = Path.Combine(mydocs, "create.txt");
if file exists, no error is thrown, overwrite old one
using FileStream fileStream = File.Create(filepath);
Technique4. Create a new File and return StreamWriter object
var mydocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string filepath = Path.Combine(mydocs, "create.txt");
//if file exists, no error is thrown
using StreamWriter streamWriter = File.CreateText(filepath);


When a new file is created, it can be written using FileStream, StreamWriter or BinaryWriter etc.

Example1. Write using FileStream
var mydocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string filepath = Path.Combine(mydocs, "create.txt");
// if file exists, overwrite it
FileStream fileStream = File.Create(filepath);
string message = "Hello, World!";
fileStream.Write(System.Text.Encoding.UTF8.GetBytes(message), 0, message.Length);
fileStream.Close();
Example2. Write using StreamWriter
var mydocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string filepath = Path.Combine(mydocs, "create.txt");
//if file exists, overwrite it
using StreamWriter streamWriter = File.CreateText(filepath);
streamWriter.WriteLine("Hello World!");
streamWriter.Write("End of line!");
Example3. Write using BinaryWriter
var mydocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string filepath = Path.Combine(mydocs, "create.txt");
File.Create(filepath).Close();
using BinaryWriter binaryWriter = new BinaryWriter(File.Open(filepath, FileMode.Open));
binaryWriter.Write("Hello BinaryWriter");

No comments:

Post a Comment

Hot Topics