October 9, 2009

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



'Like' us on our FaceBook page if you find this blog useful. Thanks!


Did you like this post?
kick it on DotNetKicks.com Save on Delicious
subscribe via rss subscribe via e-mail
print this post follow me on twitter


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

comments

1 Response to "Quickly Replace the Contents of a Text File using C# or VB.NET"
  1. Anonymous said...
    November 6, 2010 10:45 AM

    Very helpful and easy build.

 

Copyright © 2009-2012 All Rights Reserved for DevCurry.com by Suprotim Agarwal | Terms and Conditions