Saturday, October 31, 2009

Home of .net & C# (dot net, C#) code snippets, learning, how tos and common tasks

Hi All,

I have created this blog to share .net & C# (dot net, C#) code snippets, learning, how tos and common tasks.
All the posts are in draft version, as i am just gathering all my learning.

once everything gathered together, i will keep some structured posting for all my posts...

hope to see you again... :)

How to read text from file in C#

// Example #1

// Read the file as one string.
string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");

// Display the file contents to the console.
System.Console.WriteLine("Contents of writeText.txt = {0}", text);

// Example #2
// Read the file lines into a string array.
string[] lines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");

How to write text to file in C#

using (StreamWriter sw = File.CreateText(@"C:\test.txt"))
{
sw.Write("Some text");
}