Thursday, December 13, 2012

Reading and Writing Text Files c sharp


Writing to a Text 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();
       }
   }
}

Reading From a Text 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();
       }
   }
}

Fetching Web Pages


WebFetch.cs
using System;
using System.IO;
using System.Net;
using System.Text;


/// <summary>
/// Fetches a Web Page
/// </summary>
class WebFetch
{
 static void Main(string[] args)
 {
  // used to build entire input
  StringBuilder sb  = new StringBuilder();

  // used on each read operation
  byte[]        buf = new byte[8192];

  // prepare the web page we will be asking for
  HttpWebRequest  request  = (HttpWebRequest)
   WebRequest.Create("http://solve-dotnet.blogspot.in/");

  // execute the request
  HttpWebResponse response = (HttpWebResponse)
   request.GetResponse();

  // we will read data via the response stream
  Stream resStream = response.GetResponseStream();

  string tempString = null;
  int    count      = 0;

  do
  {
   // fill the buffer with data
   count = resStream.Read(buf, 0, buf.Length);

   // make sure we read some data
   if (count != 0)
   {
    // translate from bytes to ASCII text
    tempString = Encoding.ASCII.GetString(buf, 0, count);

    // continue building the string
    sb.Append(tempString);
   }
  }
  while (count > 0); // any more data to read?

  // print out page source
  Console.WriteLine(sb.ToString());
 }
}