C#/work with files in C#.net
Expert: Srini Nagarajan - 10/28/2005
Question How can I work with text files in C# .net? For example I want to open a text file, read something from it (strings or numbers) and then create a file and write something into it.
AnswerHi
I am sorry not replying imdtly!!
Here is simple example to open and write files
Listing 1: Writing Text Data to a File: TextFileWriter.cs
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();
}
}
}
Listing 2: Reading Text Data from a File: TextFileReader.cs
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();
}
}
}
Happy Programming!!
srini