3

編集:

提案に従って、次の実装を開始しました。

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

読み取ったデータを実際に返すにはどうすればよいですか?

4

2 に答える 2

2
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));
于 2013-07-12T16:57:36.307 に答える
1
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();
}
于 2013-07-12T17:05:58.263 に答える