You are here:

C#/work with files in C#.net

Advertisement


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.

Answer
Hi

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  

C#

All Answers


Answers by Expert:


Ask Experts

Volunteer


Srini Nagarajan

Expertise

can answer any kind of questions in ASP.NET, C#, VB.NET, ASP, SharePoint 2007, Coldfusion, Powerbuilder 7.00 / 8.00, JAVA servlets, MS SQL 2000 / MSSQL7, Sybase

Experience

Contact me if you need any custom development on ASP.NET, ASP, Coldfusion, Powerbuilder

©2012 About.com, a part of The New York Times Company. All rights reserved.