Reading large files in bytes

跟風遠走 提交于 2019-12-07 15:00:40

问题


EDIT:

As per the suggestion, I have started to implement the following:

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

How do I go about actually returning the data that I've read?


回答1:


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

It should not read "Random",it reads in the same order but just in case try this:

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



回答2:


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


来源:https://stackoverflow.com/questions/17618925/reading-large-files-in-bytes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!