Csharp/CSharp Tutorial/File Directory Stream/Text File Read Write — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 15:20, 26 мая 2010

Create a file called test.txt in the current directory:

<source lang="csharp">using System; using System.IO; class Program {

   static void Main() {
       using (Stream s = new FileStream("test.txt", FileMode.Create)) {
           Console.WriteLine(s.CanRead);       // true
           Console.WriteLine(s.CanWrite);      // true
           Console.WriteLine(s.CanSeek);       // true
           s.WriteByte(101);
           s.WriteByte(102);
           byte[] block = { 1, 2, 3, 4, 5 };
           s.Write(block, 0, block.Length);     // Write block of 5 bytes
           Console.WriteLine(s.Length);         // 7
           Console.WriteLine(s.Position);       // 7
           s.Position = 0;                       // Move back to the start
           Console.WriteLine(s.ReadByte());     // 101
           Console.WriteLine(s.ReadByte());     // 102
           Console.WriteLine(s.Read(block, 0, block.Length));   // 5
           Console.WriteLine(s.Read(block, 0, block.Length));   // 0
       }
   }

}</source>

Display a text file.

<source lang="csharp">using System; using System.IO;

class MainClass {

 public static void Main(string[] args) { 
   int i; 
   FileStream fin; 

   try { 
     fin = new FileStream("test.txt", FileMode.Open); 
   } catch(FileNotFoundException exc) { 
     Console.WriteLine(exc.Message); 
     return; 
   } catch(IndexOutOfRangeException exc) { 
     Console.WriteLine(exc.Message + "\nUsage: ShowFile File"); 
     return; 
   } 

   // read bytes until EOF is encountered 
   do { 
     try { 
       i = fin.ReadByte(); 
     } catch(Exception exc) { 
       Console.WriteLine(exc.Message); 
       return; 
     } 
     if(i != -1) Console.Write((char) i); 
   } while(i != -1); 

   fin.Close(); 
 } 

}</source>

Get interal StringBuilder from a StringWriter

<source lang="csharp">using System; using System.IO; using System.Text; public class MainClass {

   public static int Main(string[] args)
   {
   // Get a StringWriter and write some stuff.
   StringWriter writer = new StringWriter();
   writer.WriteLine("string 1");
   
   for(int i = 0; i < 10; i++)
   {
     writer.Write(i + " ");
   }
   writer.Write(writer.NewLine);
   writer.Close();
   Console.WriteLine("Contents:\n{0}", writer);
   
   StringBuilder str = writer.GetStringBuilder();
   string allOfTheData = str.ToString();
   Console.WriteLine("-> StringBuilder says:\n{0}", allOfTheData);
   str.Insert(20, "INSERTED STUFF");
   allOfTheData = str.ToString();
   Console.WriteLine("-> New StringBuilder says:\n{0}", allOfTheData);
   StringReader sr = new StringReader(writer.ToString());
   
   string input = null;
   while ((input = sr.ReadLine()) != null)
   {
     Console.WriteLine (input);
   }
   sr.Close();
       return 0;
   }

}</source>

Contents:
string 1
0 1 2 3 4 5 6 7 8 9
-> StringBuilder says:
string 1
0 1 2 3 4 5 6 7 8 9
-> New StringBuilder says:
string 1
0 1 2 3 4 INSERTED STUFF5 6 7 8 9
string 1
0 1 2 3 4 INSERTED STUFF5 6 7 8 9

Reading Writing To Text File

<source lang="csharp">using System; using System.IO;

   class Tester
   {
       public static void Main()
       {
           FileInfo theSourceFile = new FileInfo("test.cs");
           StreamReader reader = theSourceFile.OpenText();
           StreamWriter writer = new StreamWriter("test.bak", false);
           string text;
           do
           {
               text = reader.ReadLine();
               writer.WriteLine(text);
               Console.WriteLine(text);
           } while (text != null);
           reader.Close();
           writer.Close();
       }
   }</source>

Read text file line by line

<source lang="csharp">using System; using System.IO; class MainClass {

 public static void Main() 
 {
   FileStream outStream = File.Create("c:\\Test.txt");
   StreamWriter sw = new StreamWriter(outStream);
   sw.WriteLine("This is a test of the StreamWriter class");
   sw.Flush();
   sw.Close();
   StreamReader sr = new StreamReader("c:\\Test.txt");
   string FirstLine;
 
   FirstLine = sr.ReadLine();
   Console.WriteLine(FirstLine);
   sr.Close();
 }

}</source>

Read/Write text file using the StringWriter

<source lang="csharp">using System; using System.IO; using System.Text; public class MainClass {

   public static int Main(string[] args)
   {
   // Get a StringWriter and write some stuff.
   StringWriter writer = new StringWriter();
   writer.WriteLine("string 1");
   
   for(int i = 0; i < 10; i++)
   {
     writer.Write(i + " ");
   }
   writer.Write(writer.NewLine);
   writer.Close();
   Console.WriteLine("Contents:\n{0}", writer);
   
   StringBuilder str = writer.GetStringBuilder();
   string allOfTheData = str.ToString();
   Console.WriteLine("-> StringBuilder says:\n{0}", allOfTheData);
   str.Insert(20, "INSERTED STUFF");
   allOfTheData = str.ToString();
   Console.WriteLine("-> New StringBuilder says:\n{0}", allOfTheData);
   StringReader sr = new StringReader(writer.ToString());
   
   string input = null;
   while ((input = sr.ReadLine()) != null)
   {
     Console.WriteLine (input);
   }
   sr.Close();
       return 0;
   }

}</source>

Contents:
string 1
0 1 2 3 4 5 6 7 8 9
-> StringBuilder says:
string 1
0 1 2 3 4 5 6 7 8 9
-> New StringBuilder says:
string 1
0 1 2 3 4 INSERTED STUFF5 6 7 8 9
string 1
0 1 2 3 4 INSERTED STUFF5 6 7 8 9

Simple IO with the File Type

<source lang="csharp">using System; using System.IO; class Program {

 static void Main(string[] args)
 {
   string[] myTasks = {"A", "C","C", "P"};
   File.WriteAllLines(@"C:\tasks.txt", myTasks);
   foreach (string task in File.ReadAllLines(@"C:\tasks.txt"))
   {
     Console.WriteLine("TODO: {0}", task);
   }
 }

}</source>

Use while loop to read a text file

<source lang="csharp">using System; using System.IO; class MainClass {

 public static void Main(string[] args)
 {
   try
   {
     StreamReader sr = File.OpenText("c:\\boot.ini");
     string strLine;
     while(null != (strLine = sr.ReadLine()))
     {
       Console.WriteLine(strLine);
     }
     sr.Close();
   }
   catch(FileNotFoundException e)
   {
     Console.WriteLine(e.Message);
   }
 }

}</source>

[boot loader]
timeout=30
default=multi(0)disk(0)rdisk(0)partition(1)\WINDOWS
[operating systems]
multi(0)disk(0)rdisk(0)partition(1)\WINDOWS="Microsoft Windows XP Home Edition" /noexecute=optin /fa
stdetect

Write and read text file using StreamWriter

<source lang="csharp">using System; using System.IO; public class MainClass {

   public static int Main(string[] args)
   {
   FileInfo f = new FileInfo("test.txt");
   StreamWriter writer = f.CreateText();
   writer.WriteLine("string 1");
   writer.WriteLine("string 2");
   
   for(int i = 0; i < 10; i++)
   {
     writer.Write(i + " ");
   }
   writer.Write(writer.NewLine);
   writer.Close();
   // Now read it all back in.
   StreamReader sr = File.OpenText("test.txt");
   string input = null;
   while ((input = sr.ReadLine()) != null)
   {
     Console.WriteLine (input);
   }
       return 0;
   }

}</source>

string 1
string 2
0 1 2 3 4 5 6 7 8 9

Write text file line by line

<source lang="csharp">using System; using System.IO; class MainClass {

 public static void Main() 
 {
   FileStream outStream = File.Create("c:\\Test.txt");
   StreamWriter sw = new StreamWriter(outStream);
   sw.WriteLine("This is a test of the StreamWriter class");
   sw.Flush();
   sw.Close();
   StreamReader sr = new StreamReader("c:\\Test.txt");
   string FirstLine;
 
   FirstLine = sr.ReadLine();
   Console.WriteLine(FirstLine);
   sr.Close();
 }

}</source>

Write to a file

<source lang="csharp">using System; using System.IO;

class MainClass {

 public static void Main(string[] args) { 
   FileStream fout; 

   // open output file 
   try { 
     fout = new FileStream("test.txt", FileMode.Create); 
   } catch(IOException exc) { 
     Console.WriteLine(exc.Message + "\nError Opening Output File"); 
     return; 
   } 

   // Write the alphabet to the file. 
   try { 
     for(char c = "A"; c <= "Z"; c++) 
       fout.WriteByte((byte) c); 
   } catch(IOException exc) { 
     Console.WriteLine(exc.Message + "File Error"); 
   } 

   fout.Close(); 
 } 

}</source>