Csharp/CSharp Tutorial/File Directory Stream/Stream

Материал из .Net Framework эксперт
Версия от 15:20, 26 мая 2010; Admin (обсуждение | вклад) (1 версия)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

C#"s I/O Is Built Upon Streams

  1. C# programs perform I/O through streams.
  2. A stream is linked to a physical device by the C# I/O system.
  3. The I/O classes and methods can be applied to many types of devices.

At the lowest level, all C# I/O systems operate on bytes.

The Predefined Streams

  1. Console.Out: the standard output stream.
  2. Console.In: standard input, which is by default the keyboard.
  3. Console.Error: the standard error stream, which is also the console by default.

15.18.Stream 15.18.1. C#"s I/O Is Built Upon Streams 15.18.2. <A href="/Tutorial/CSharp/0300__File-Directory-Stream/TheStreamClasses.htm">The Stream Classes</a> 15.18.3. <A href="/Tutorial/CSharp/0300__File-Directory-Stream/TheByteStreamClassesandTheCharacterStreamWrapperClasses.htm">The Byte Stream Classes and The Character Stream Wrapper Classes</a> 15.18.4. <A href="/Tutorial/CSharp/0300__File-Directory-Stream/StreamseekingSeekOriginCurrentSeekOriginBeginSeekOriginEnd.htm">Stream seeking: SeekOrigin.Current, SeekOrigin.Begin, SeekOrigin.End</a> 15.18.5. <A href="/Tutorial/CSharp/0300__File-Directory-Stream/Usingstreamreadertodecodestreams.htm">Using streamreader to decode streams</a> 15.18.6. <A href="/Tutorial/CSharp/0300__File-Directory-Stream/Usingstreamreadertoreadentirelinesatatime.htm">Using streamreader to read entire lines at a time</a> 15.18.7. <A href="/Tutorial/CSharp/0300__File-Directory-Stream/Usingstreamreadertoreadtheentirestreamatonce.htm">Using streamreader to read the entire stream at once</a> 15.18.8. <A href="/Tutorial/CSharp/0300__File-Directory-Stream/Readingfromastreamcastingtochars.htm">Reading from a stream, casting to chars</a> 15.18.9. <A href="/Tutorial/CSharp/0300__File-Directory-Stream/Readingfromastreambufferatatime.htm">Reading from a stream buffer at a time</a> 15.18.10. <A href="/Tutorial/CSharp/0300__File-Directory-Stream/ImplementingBinaryReadWriteToFile.htm">Implementing Binary Read Write To File</a>

Implementing Binary Read Write To File

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

   class Tester
   {
       public static void Main()
       {
           int SizeBuff = 1024;
            Stream inputStream = File.OpenRead("test1.cs");
           Stream outputStream = File.OpenWrite("test1.bak");
           byte[] buffer = new Byte[SizeBuff];
           int bytesRead;
           while ((bytesRead =
           inputStream.Read(buffer, 0, SizeBuff)) > 0)
           {
               outputStream.Write(buffer, 0, bytesRead);
           }
           inputStream.Close();
           outputStream.Close();
       }
   }</source>

Reading from a stream buffer at a time

<source lang="csharp">using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.IO.rupression; using System.Net; using System.Net.Mail; using System.Runtime.InteropServices; using System.Text; using System.Threading; public class MainClass {

   public static void Main()
   {
       using (Stream s = new FileStream("c:\\test.txt", FileMode.Open))
       {
           int readCount;
           byte[] buffer = new byte[4096];
           while ((readCount = s.Read(buffer, 0, buffer.Length)) != 0)
           {
               for (int i = 0; i < readCount; i++)
               {
                   Console.Write("{0} ", buffer[i]);
               }
           }
       }
   }

}</source>

Reading from a stream, casting to chars

<source lang="csharp">using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.IO.rupression; using System.Net; using System.Net.Mail; using System.Runtime.InteropServices; using System.Text; using System.Threading; public class MainClass {

   public static void Main()
   {
       using (Stream s = new FileStream("c:\\test.txt", FileMode.Open))
       {
           int read;
           while ((read = s.ReadByte()) != -1)
           {
               Console.Write("{0} ", (char)read);
           }
       }
   }

}</source>

Stream seeking: SeekOrigin.Current, SeekOrigin.Begin, SeekOrigin.End

<source lang="csharp">using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.IO.rupression; using System.Net; using System.Net.Mail; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Threading; public class MainClass {

   public static void Main()
   {
       using (Stream s = new FileStream("c:\\test.txt", FileMode.Open))
       {
           s.Seek(8, SeekOrigin.Current);
           Console.WriteLine(s.ReadByte());
           s.Seek(0, SeekOrigin.Begin);
           Console.WriteLine(s.ReadByte());
           s.Seek(-1, SeekOrigin.End);
           Console.WriteLine(s.ReadByte());
       }
   }

}</source>

The Byte Stream Classes and The Character Stream Wrapper Classes

The Byte Stream Classes

Stream Class Description BufferedStream Wraps a byte stream and adds buffering. FileStream A byte stream designed for file I/O. MemoryStream A byte stream that uses memory for storage.

The Character Stream Wrapper Classes.

To create a character stream, wrap a byte stream inside one of C#"s character stream wrappers.

  1. The abstract classes TextReader and TextWriter are at the top of the character stream hierarchy.
  2. TextReader handles input.
  3. TextWriter handles output.

The Stream Classes

  1. System.IO.Stream represents a byte stream
  2. System.IO.Stream is a base class for all other stream classes.
  3. System.IO.Stream is abstract.

Some of the Methods Defined by Stream

Method Description void Close() Closes the stream. void Flush() Flush the stream. int ReadByte() Returns an integer representation of a byte of input. Returns -1 if no byte is available. int Read(byte[ ] buf,int offset, int numBytes) Attempts to read up to numBytes bytes into buf starting at buf[offset], returning the number of bytes successfully read. long Seek(long offset,SeekOrigin origin) Sets the current position in the stream to the specified offset from the specified origin. void WriteByte(byte b) Writes a single byte to an output stream. void Write(byte[ ] buf,int offset, int numBytes) Writes a subrange of numBytes bytes from the array buf, beginning at buf[offset].

The Properties Defined by Stream

Method Description bool CanRead can be read or not. (read-only) bool CanSeek supports position requests or not. (read-only) bool CanWrite can be written or not. (read-only) long Length the length of the stream. (read-only) long Position the current position of the stream. (read/write)

Using streamreader to decode streams

<source lang="csharp">using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.IO.rupression; using System.Net; using System.Net.Mail; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Threading; public class MainClass {

   public static void Main()
   {
       Stream s = new FileStream("c:\\test.txt", FileMode.Open);
       using (StreamReader sr = new StreamReader(s, Encoding.UTF8))
       {
           int readCount;
           char[] buffer = new char[1024];
           while ((readCount = sr.Read(buffer, 0, 1024)) != 0)
           {
               for (int i = 0; i < readCount; i++)
               {
                   Console.Write("{0} ", buffer[i]);
               }
           }
       }
   }

}</source>

Using streamreader to read entire lines at a time

<source lang="csharp">using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.IO.rupression; using System.Net; using System.Net.Mail; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Threading; public class MainClass {

   public static void Main()
   {
       Stream s = new FileStream("c:\\test.txt", FileMode.Open);
       using (StreamReader sr = new StreamReader(s, Encoding.UTF8))
       {
           string line;
           while ((line = sr.ReadLine()) != null)
           {
               Console.WriteLine(line);
           }
       }
   }

}</source>

Using streamreader to read the entire stream at once

<source lang="csharp">using System; using System.Collections.Generic; using System.Collections.Specialized; using System.IO; using System.IO.rupression; using System.Net; using System.Net.Mail; using System.Net.Sockets; using System.Runtime.InteropServices; using System.Text; using System.Threading; public class MainClass {

   public static void Main()
   {
  
       Stream s = new FileStream("c:\\test.txt", FileMode.Open);
       using (StreamReader sr = new StreamReader(s, Encoding.UTF8))
       {
           Console.WriteLine(sr.ReadToEnd());
       }
   }

}</source>