Csharp/CSharp Tutorial/File Directory Stream/File Byte Read Write

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

Reading from a stream one byte at a time

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))
        {
            int read;
            while ((read = s.ReadByte()) != -1)
            {
                Console.Write("{0} ", read);
            }
        }
    }
}

Use FileStream to read a file by byte array

using System;
using System.Windows.Forms;
using System.IO;
class MainClass
{
  public static void Main() 
  {
    FileStream inStream = File.OpenRead("C:\\test.txt");
    FileStream outStream = File.OpenWrite("C:\\test.txt" + ".bak");
    byte[] buf = new byte[4096];
    int bytesRead;
    while ((bytesRead = inStream.Read(buf, 0, 4096)) > 0)
      outStream.Write(buf, 0, bytesRead);
    outStream.Flush();
    outStream.Close();
    inStream.Close();
  }
}

Use FileStream to write a file by byte array

using System;
using System.Windows.Forms;
using System.IO;
class MainClass
{
  public static void Main() 
  {
    FileStream inStream = File.OpenRead("C:\\test.txt");
    FileStream outStream = File.OpenWrite("C:\\test.txt" + ".bak");
    byte[] buf = new byte[4096];
    int bytesRead;
    while ((bytesRead = inStream.Read(buf, 0, 4096)) > 0)
      outStream.Write(buf, 0, bytesRead);
    outStream.Flush();
    outStream.Close();
    inStream.Close();
  }
}