(c#) write to text file

(c#) write to text file C#-write-Text-File

Write to text file is one of the code required in almost all programming languages. Here we will see C#.net and VB.net program. Program will create directory at specified path and write text file.

Write text file (C#.net)

System.IO is the namespace used for file and directory operations. Before writing the file at specified directory, we need to check whether directory exists or not. Directory.Create method creates directory at specified path.

C# write text file example
using System;
using System.IO;
namespace Csharp.WriteFile.Example
{
class Program
{
static void Main(string[] args)
{
string directoryPath = @"c:\xxx";
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
FileStream fs = new FileStream(@"c:\xxx\ReadMe.txt", FileMode.OpenOrCreate);
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("This is first line");
sw.WriteLine("This is second line");
sw.Write("This is third line");
sw.Flush();
sw.Close();
fs.Close();
Console.ReadLine();
}
}
}
VB.net write text file example
Imports System.IO
Namespace Csharp.WriteFile.Example
Class Program
Private Shared Sub Main(args As String())
Dim directoryPath As String = "c:\xxx"
If Not Directory.Exists(directoryPath) Then
Directory.CreateDirectory(directoryPath)
End If
Dim fs As New FileStream("c:\xxx\ReadMe.txt", FileMode.OpenOrCreate)
Dim sw As New StreamWriter(fs)
sw.WriteLine("This is first line")
sw.WriteLine("This is second line")
sw.Write("This is third line")
sw.Flush()
sw.Close()
fs.Close()
Console.ReadLine()
End Sub
End Class
End Namespace
Output

FileStream instance is passed to StreamWriter constructor. WriteLine method of StreamWriter instance is write the content to specified file at specified location.

When we called Flush method of Stream Writer instance, it saves the content to FileStream. and as soon we call Close method of FileStream instance it saves the content to Hard Drive.

Tags: