This is a discussion on How to Read and write txt file using C# within the C# Programming forums, part of the Software Development category; How to Read and write txt file using C#...
| |||||||
| Register | FAQ | Members List | Calendar | Mark Forums Read |
| |||
| Reading and Writing Text file: Reading: using System; using System.IO; namespace csharp_station.howto { class TextFileReader { static void Main(string[] args) { // create reader & open file Textreader tr = new StreamReader("date.txt"); // read a line of text Console.WriteLine(tr.ReadLine()); // close the stream tr.Close(); } } } Writing: using System; using System.IO; namespace csharp_station.howto { class TextFileWriter { static void Main(string[] args) { // create a writer and open the file TextWriter tw = new StreamWriter("date.txt"); // write a line of text to the file tw.WriteLine(DateTime.Now); // close the stream tw.Close(); } } } |
| |||
| We can read the file using File class as follows, Code: //Read a txt file
string[] str = File.ReadAllLines(@"C:/test.txt");
if (str.Length > 0)
{
for (int i = 0; i < str.Length; i++)
{
MessageBox.Show(str[i]);
}
} We can write the file using StreamWriter as follows, Code: //Write a txt file
StreamWriter sw = new StreamWriter("C:/test.txt");
string str = "Test for writing";
sw.WriteLine(str);
sw.Close();
__________________ S.VinothkumaR Behind me is infinite power, Before me is Endless Possibility, Around me is Boundless Opportunity, Why should I fear! |
![]() |
| Thread Tools | |
| Display Modes | |
| |
Similar Threads | ||||
| Thread | Thread Starter | Forum | Replies | Last Post |
| Attempted to read write protected memory | Balasubramanian.S | C# Programming | 0 | 03-21-2008 09:47 PM |
| How to read the text from a .pdf file? | vadivelanvaidyanathan | Software Testing | 0 | 01-28-2008 10:15 PM |
| How to read and write System Registry Keys using C# (VS.Net 2005) | oxygen | C# Programming | 2 | 08-31-2007 11:41 PM |
| Read and Write IPTC and EXIF metadata fro raw Images | Balasubramanian.S | C# Programming | 4 | 08-03-2007 07:38 AM |
| Method in read the file | prasath | Java Programming | 1 | 07-17-2007 12:12 AM |