Csharp/CSharp Tutorial/File Directory Stream/FileStream

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

Binary File Reading through FileStream

using System;
using System.Collections.Generic;
using System.ruponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
public class MainClass {
    public static void Main() {
        int nCols = 16;
        FileStream inStream = new FileStream("c:\\a.txt", FileMode.Open, FileAccess.Read);
        long nBytesToRead = inStream.Length;
        if (nBytesToRead > 65536 / 4)
            nBytesToRead = 65536 / 4;
        int nLines = (int)(nBytesToRead / nCols) + 1;
        string[] lines = new string[nLines];
        int nBytesRead = 0;
        for (int i = 0; i < nLines; i++) {
            StringBuilder nextLine = new StringBuilder();
            nextLine.Capacity = 4 * nCols;
            for (int j = 0; j < nCols; j++) {
                int nextByte = inStream.ReadByte();
                nBytesRead++;
                if (nextByte < 0 || nBytesRead > 65536)
                    break;
                char nextChar = (char)nextByte;
                if (nextChar < 16)
                    nextLine.Append(" x0" + string.Format("{0,1:X}", (int)nextChar));
                else if
                    (char.IsLetterOrDigit(nextChar) || char.IsPunctuation(nextChar))
                    nextLine.Append("  " + nextChar + " ");
                else
                    nextLine.Append(" x" + string.Format("{0,2:X}", (int)nextChar));
            }
        }
        inStream.Close();

    }
}

Demonstrate random access file

using System; 
using System.IO;  
 
class MainClass { 
  public static void Main() { 
    FileStream f; 
    char ch; 
 
    try { 
      f = new FileStream("random.dat", FileMode.Create); 
    } 
    catch(IOException exc) { 
      Console.WriteLine(exc.Message); 
      return ; 
    } 
 
    // Write the alphabet.      
    for(int i=0; i < 26; i++) { 
      try { 
        f.WriteByte((byte)("A"+i)); 
      }  
      catch(IOException exc) { 
        Console.WriteLine(exc.Message); 
        return ; 
      } 
    } 
 
    try { 
      f.Seek(0, SeekOrigin.Begin); // seek to first byte 
      ch = (char) f.ReadByte(); 
      Console.WriteLine("First value is " + ch); 
 
      f.Seek(1, SeekOrigin.Begin); // seek to second byte 
      ch = (char) f.ReadByte(); 
      Console.WriteLine("Second value is " + ch); 
 
      f.Seek(4, SeekOrigin.Begin); // seek to 5th byte 
      ch = (char) f.ReadByte(); 
      Console.WriteLine("Fifth value is " + ch); 
 
      Console.WriteLine(); 
 
    }  
    catch(IOException exc) { 
      Console.WriteLine(exc.Message); 
    } 
  
    Console.WriteLine(); 
    f.Close(); 
  } 
}
First value is A
Second value is B
Fifth value is E

Is a stream seekable

using System;
using System.IO;
public class MainClass {
    public static void Main() {
        byte[] buf2 = new byte[] { 97, 112, 112, 108, 101, 115, 97, 117, 99, 101 };
        FileStream s = new FileStream("Foo.txt", FileMode.Open);
        Console.WriteLine("Length: {0}, Position: {1}", s.Length, s.Position);
        if (s.CanSeek) {
            s.Seek(13, SeekOrigin.Begin);
            Console.WriteLine(
                "Position: {0}", s.Position);
            s.Write(buf2, 0, buf2.Length);
        }
    }
}

Move file pointer to beginning of file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
    class Program
    {
        static void Main(string[] args)
        {
            FileStream aFile = new FileStream("Temp.txt", FileMode.Create);
            char[] charData = "this is a test.".ToCharArray();
            byte[] byData = new byte[charData.Length];
            Encoder e = Encoding.UTF8.GetEncoder();
            e.GetBytes(charData, 0, charData.Length, byData, 0, true);
            // Move file pointer to beginning of file.
            aFile.Seek(0, SeekOrigin.Begin);
            aFile.Write(byData, 0, byData.Length);
        }
    }

Open a file with exception handling

FileStream fin; 
 
try { 
  fin = new FileStream("test.dat", FileMode.Open); 
} 
catch(FileNotFoundException exc) { 
  Console.WriteLine(exc.Message); 
  return; 
} 
catch { 
  Console.WriteLine("Cannot open file."); 
  return; 
}

Open an existing file

using System;
using System.IO;
public class MainClass
{
  static void Main(string[] args)
  {
    FileInfo MyFile = new FileInfo(@"c:\Testing.txt");
    FileStream MyStream;
    MyStream = MyFile.Open(FileMode.Open, FileAccess.Read, FileShare.None);
  }
}

Read every other value using FileSeek

using System; 
using System.IO;  
 
class MainClass { 
  public static void Main() { 
    FileStream f; 
    char ch; 
 
    try { 
      f = new FileStream("random.dat", FileMode.Create); 
    } 
    catch(IOException exc) { 
      Console.WriteLine(exc.Message); 
      return ; 
    } 
 
    // Write the alphabet.      
    for(int i=0; i < 26; i++) { 
      try { 
        f.WriteByte((byte)("A"+i)); 
      }  
      catch(IOException exc) { 
        Console.WriteLine(exc.Message); 
        return ; 
      } 
    } 
 
    try { 
      Console.WriteLine("Here is every other value: "); 
      for(int i=0; i < 26; i += 2) { 
        f.Seek(i, SeekOrigin.Begin); // seek to ith double 
        ch = (char) f.ReadByte(); 
        Console.Write(ch + " "); 
      } 
 
    }  
    catch(IOException exc) { 
      Console.WriteLine(exc.Message); 
    } 
  
    Console.WriteLine(); 
    f.Close(); 
  } 
}
Here is every other value:
A C E G I K M O Q S U W Y

Read file stream as an array of bytes

using System;
using System.IO;
public class MainClass
{
  static void Main(string[] args)
  {
    FileStream MyFileStream1 = new FileStream(@"c:\Testing.txt", FileMode.Create);
    int NumberOfBytes = 200;
    byte[] MyByteArray = new Byte[NumberOfBytes];
    int BytesRead = MyFileStream1.Read(MyByteArray, 0, NumberOfBytes);
    
    MyFileStream1.Close();    
  }
}

Read file stream on a per byte basis

using System;
using System.IO;
public class MainClass
{
  static void Main(string[] args)
  {
    FileStream MyFileStream1 = new FileStream(@"c:\Testing.txt", FileMode.Create);
    
    int MyBytes = MyFileStream1.ReadByte();
    
    MyFileStream1.Close();    
  }
}

Reset internal position for a FileStream

using System;
using System.IO;
public class MainClass
{
    public static int Main(string[] args)
    {      
    FileInfo f = new FileInfo(@"C:\test.txt");
    FileStream  s = f.Open(FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);    
    for(int i = 0; i < 256; i++)
    {
      s.WriteByte((byte)i);
    }
    // Reset internal position.
    s.Position = 0;
    for(int i = 0; i < 256; i++)
    {
      Console.Write(s.ReadByte());  
    }
    s.Close();
    f.Delete();
        return 0;
    }
}

Text File Reading with FileStream

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
    class Program
    {
        static void Main(string[] args)
        {
            byte[] byData = new byte[200];
            char[] charData = new Char[200];
            FileStream aFile = new FileStream("Program.cs", FileMode.Open);
            aFile.Seek(113, SeekOrigin.Begin);
            aFile.Read(byData, 0, 200);
            Decoder d = Encoding.UTF8.GetDecoder();
            d.GetChars(byData, 0, byData.Length, charData, 0);
            Console.WriteLine(charData);
        }
    }

The FileMode and FileAccess

Value Description FileMode.Append append to the end of file. FileMode.Create create a new output file. Any preexisting file by the same name will be destroyed. FileMode.CreateNew create a new output file. The file must not already exist. FileMode.Open open a preexisting file. FileMode.OpenOrCreate open a file if it exists, or create the file if it does not already exist. FileMode.Truncate open a preexisting file, but reduce its length to zero.

If you want to restrict access to just reading or just writing, use this constructor:


FileStream(string filename, FileMode mode, FileAccess how)

Use FileStream to read a file byte by byte

using System;
using System.Windows.Forms;
using System.IO;
class MainClass
{
  public static void Main() 
  {
    OpenFileDialog dlgOpen = new OpenFileDialog();
    dlgOpen.Title="Select file to back up";
    if (dlgOpen.ShowDialog() == DialogResult.OK)
    {
      FileStream inStream = File.OpenRead(dlgOpen.FileName);
      FileStream outStream =  File.OpenWrite(dlgOpen.FileName + ".bak");
      int b;
      while ((b = inStream.ReadByte()) > -1)
        outStream.WriteByte( (byte) b);
      outStream.Flush();
      outStream.Close();
      inStream.Close();
    }
  }
}

Use FileStream to read a file selected from OpenFileDialog

using System;
using System.Windows.Forms;
using System.IO;
class MainClass
{
  public static void Main() 
  {
    OpenFileDialog dlgOpen = new OpenFileDialog();
    dlgOpen.Title="Select file to back up";
    if (dlgOpen.ShowDialog() == DialogResult.OK)
    {
      FileStream inStream = File.OpenRead(dlgOpen.FileName);
      FileStream outStream =  File.OpenWrite(dlgOpen.FileName + ".bak");
      int b;
      while ((b = inStream.ReadByte()) > -1)
        outStream.WriteByte( (byte) b);
      outStream.Flush();
      outStream.Close();
      inStream.Close();
    }
  }
}

Use FileStream to write/read a file byte by byte

using System;
using System.Windows.Forms;
using System.IO;
class MainClass
{
  public static void Main() 
  {
    OpenFileDialog dlgOpen = new OpenFileDialog();
    dlgOpen.Title="Select file to back up";
    if (dlgOpen.ShowDialog() == DialogResult.OK)
    {
      FileStream inStream = File.OpenRead(dlgOpen.FileName);
      FileStream outStream =  File.OpenWrite(dlgOpen.FileName + ".bak");
      int b;
      while ((b = inStream.ReadByte()) > -1)
        outStream.WriteByte( (byte) b);
      outStream.Flush();
      outStream.Close();
      inStream.Close();
    }
  }
}

using statement and FileStream

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
  class Program
  {
    static void Main(string[] args)
    {
      using (FileStream fStream = File.Open(@"C:\myMessage.dat",FileMode.Create))
      {
        string msg = "Hello!";
        byte[] msgAsByteArray = Encoding.Default.GetBytes(msg);
        fStream.Write(msgAsByteArray, 0, msgAsByteArray.Length);
        fStream.Position = 0;
        byte[] bytesFromFile = new byte[msgAsByteArray.Length];
        for (int i = 0; i < msgAsByteArray.Length; i++)
        {
          bytesFromFile[i] = (byte)fStream.ReadByte();
          Console.Write(bytesFromFile[i]);
        }
        Console.WriteLine(Encoding.Default.GetString(bytesFromFile));
      }
    }
  }

Write byte array with FileStream

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
    class Program
    {
        static void Main(string[] args)
        {
            FileStream aFile = new FileStream("Temp.txt", FileMode.Create);
            char[] charData = "this is a test.".ToCharArray();
            byte[] byData = new byte[charData.Length];
            Encoder e = Encoding.UTF8.GetEncoder();
            e.GetBytes(charData, 0, charData.Length, byData, 0, true);
            // Move file pointer to beginning of file.
            aFile.Seek(0, SeekOrigin.Begin);
            aFile.Write(byData, 0, byData.Length);
        }
    }

Write data to file through FileStream per byte

using System;
using System.IO;
public class MainClass
{
  static void Main(string[] args)
  {
    FileStream MyFileStream1 = new FileStream(@"c:\Testing.txt", FileMode.Create);
    byte MyWriteByte = 100;
    MyFileStream1.WriteByte(MyWriteByte);
    
    MyFileStream1.Close();    
  }
}

Write data to file through FileStream via an array

using System;
using System.IO;
public class MainClass
{
  static void Main(string[] args)
  {
    FileStream MyFileStream1 = new FileStream(@"c:\Testing.txt", FileMode.Create);
    int NumberOfBytesToWrite = 256;
    byte[] MyWriteByteArray = new Byte[NumberOfBytesToWrite];
    for (int i = 0; i < 256; i++)
    {
      MyWriteByteArray[i] = (byte)i;
      i++;
    }
    MyFileStream1.Write(MyWriteByteArray, 0, NumberOfBytesToWrite);
    
    MyFileStream1.Close();    
  }
}

Write/read bytes using FileStream

using System;
using System.IO;
public class MainClass
{
    public static int Main(string[] args)
    {
    FileStream myFStream = new FileStream("test.dat", FileMode.OpenOrCreate, FileAccess.ReadWrite);
      
    for(int i = 0; i < 256; i++)
      myFStream.WriteByte((byte)i);
    myFStream.Position = 0;
    for(int i = 0; i < 256; i++)
      Console.Write(myFStream.ReadByte());  
    Console.WriteLine();
    myFStream.Close();
    return 0;
    }
}
0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
5556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021
0310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513
6137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
1701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022
0320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523
6237238239240241242243244245246247248249250251252253254255