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



Will you give this article a +1 ? Thanks in advance


About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Anonymous said...

Very helpful and easy build.