C# 以字节为单位读取大文件

C# 以字节为单位读取大文件,c#,filestream,C#,Filestream,编辑: 根据建议,我已开始实施以下措施: private string Reading (string filePath) { byte[] buffer = new byte[100000]; FileStream strm = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 1024, FileOptions.Asynchronous)

编辑:

根据建议,我已开始实施以下措施:

 private string Reading (string filePath)
    {
        byte[] buffer = new byte[100000];

        FileStream strm = new FileStream(filePath, FileMode.Open, FileAccess.Read,
        FileShare.Read, 1024, FileOptions.Asynchronous);

        // Make the asynchronous call
        IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length, new 
        AsyncCallback(CompleteRead), strm);

    }

       private void CompleteRead(IAsyncResult result)
    {
        FileStream strm = (FileStream)result.AsyncState;

        strm.Close();
    }
我该如何实际返回我读取的数据

public static byte[] myarray;

static void Main(string[] args)
{

    FileStream strm = new FileStream(@"some.txt", FileMode.Open, FileAccess.Read,
        FileShare.Read, 1024, FileOptions.Asynchronous);

    myarray = new byte[strm.Length];
    IAsyncResult result = strm.BeginRead(myarray, 0, myarray.Length, new
    AsyncCallback(CompleteRead),strm );
    Console.ReadKey();
}

    private static void CompleteRead(IAsyncResult result)
    {
          FileStream strm = (FileStream)result.AsyncState;
          int size = strm.EndRead(result);

          strm.Close();
          //this is an example how to read data.
          Console.WriteLine(BitConverter.ToString(myarray, 0, size));
    }
它不应该读“Random”,它以相同的顺序读,但以防万一,请尝试以下方法:

Console.WriteLine(Encoding.ASCII.GetString(myarray));

处理大型文件时,建议使用
异步I/O
。另外,请阅读这篇文章:扩展netscape,beginread方法是您应该看到的。旁注:在这段代码中,您使用了for循环,但没有使用i。也许只要用while((hexInt=fs.ReadByte())!=-1)?@NETscape你能看看我的编辑吗?用
strm.Length
像terry的答案那样设置缓冲区会更好,否则我相信在完成之前会尝试读取1000000字节。非常感谢。它似乎在以随机顺序读取数据。有没有办法阻止这种事情发生?你说的随机顺序是什么意思?
BitConverter
是否将数据转换为大的或小的尾端,使其看起来很混乱,但不是吗?
private static byte[] buffer = new byte[100000];

private string ReadFile(string filePath)
{
    FileStream strm = new FileStream(filePath, FileMode.Open, FileAccess.Read,
    FileShare.Read, 1024, FileOptions.Asynchronous);

    // Make the asynchronous call
    IAsyncResult result = strm.BeginRead(buffer, 0, buffer.Length, new 
    AsyncCallback(CompleteRead), strm);

    //AsyncWaitHandle.WaitOne tells you when the operation is complete
    result.AsyncWaitHandle.WaitOne();

    //After completion, your know your data is in your buffer
    Console.WriteLine(buffer);

    //Close the handle
    result.AsyncWaitHandle.Close();
}

private void CompleteRead(IAsyncResult result)
{
    FileStream strm = (FileStream)result.AsyncState;
    int size = strm.EndRead(result);

    strm.Close();
}