Quantcast
Channel: AuthorCode » System.IO
Viewing all articles
Browse latest Browse all 4

Create or open text file to write the text in c#

0
0

If you want to to create a text file and write the text and if the file already exist then just append the text in the new line using C#, you can use the following code snippet in c#.

The following example creates or open a file to write the text.

  1. string path = @”c:\temp\MyTest.txt";
  2. using (StreamWriter sw = File.CreateText(path))
  3.   {
  4.      sw.WriteLine("Hello");
  5.      sw.WriteLine("And");
  6.      sw.WriteLine("Welcome");
  7.   }

How to open the file to read using File.OpenText() method

You can also use the following code for opening the file to read.

  1. using (StreamReader sr = File.OpenText(path))
  2. {
  3.    string s = "";
  4.    while ((s = sr.ReadLine()) != null)
  5.       {
  6.           Console.WriteLine(s);
  7.       }
  8. }

You can see above that we are reading the each line from the text file. however there are several ways to read the text file you can see this : Different methods for reading text file in C# .


Viewing all articles
Browse latest Browse all 4

Latest Images

Trending Articles





Latest Images