C # Methods for reading and writing files

Source: Internet
Author: User

17.3.1 read and write in text mode

The SteamReader and StreamWriter classes provide a way for us to read and write data in text mode. The following example reads the content from a text file and prints it on the screen.

Program Listing 17-5:

Using System;
Using System.IO;
Class Filetest
{public
 static void Main ()
 {
  StreamReader srd;
  try{
     srd=file.opentext ("C:\\c#\\file1\\file1.txt");
  }
  Catch
  {
   Console.WriteLine ("File Open Failed");
   return;
  }
  while (SRD. Peek ()!=-1)
  {
   String str=srd. ReadLine ();
   Console.WriteLine (str);
  Console.WriteLine ("The end of the file has been reached");
  Srd. Close ();
 }
}

The method used above OpenText is a static method of the file class and cannot be invoked by an instance of a specific file class. It represents reading a text stream from an existing text file and saving it in a StreamReader instance. The following example writes a text stream to a text file.

Program Listing 17-6:

Using System;
Using System.IO;
Class Filetest
{public
 static void Main ()
 {
  StreamWriter SRD;
  try{
    srd=file.createtext ("C:\\c#\\file1\\file2.txt");
  }
  Catch
  {
   Console.WriteLine ("File create Failed");
   return;
  }
  Srd. WriteLine ("Web address:");
  Srd. WriteLine ("www.bianceng.cn");
  Srd. WriteLine ("Www.263.net");
  Srd.writeline ("Www.microsoft.com/china");
  Srd. WriteLine ("www.sina.com.cn");
  Srd. Close ();
 }
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.