正在读取以字节为单位的大文件

本文关键字:文件 为单位 字节 读取 | 更新日期: 2023-09-27 18:22:04

编辑:

根据建议,我已经开始实施以下内容:

 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));
    }

它不应该读"随机",它以相同的顺序读取,但只是为了以防万一,试试这个:

Console.WriteLine(Encoding.ASCII.GetString(myarray));
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();
}