Quickly Replace the Contents of a Text File using C# or VB.NET

In this post, I will show you how to use the File class to quickly replace the contents of a Text File. Check the contents of the Sample.txt file given below.

image

We will replace the @ with [attherate] and also list the emails one after the other separated by a semicolon(;). Here’s the code to do so:

C#

try
{
string replaceString = string.Join(";",
File.ReadAllLines("D:\\sample.txt")
).Replace("@", "[attherate]");

File.WriteAllText("D:\\sample.txt", replaceString);
Console.WriteLine("Done");
Console.ReadLine();
}
catch (Exception ex)
{
// handle ex
}

VB.NET

Try
Dim
replaceString As String = String.Join(";", _
File.ReadAllLines("D:\sample.txt")).Replace("@", "[attherate]")

File.WriteAllText("D:\sample.txt", replaceString)
Console.WriteLine("Done")
Console.ReadLine()
Catch ex As Exception
' handle ex
End Try

After running the code, the output is as shown below

image

1 comment: