Need a asynchronous file reader without knowing the size
I need a method that reads a file to a byte array asynchronously but i don;t know what size the file will be (it can be a few Kb of a good few Mb).
I've tried FileStream to get the length and use BeginRead, but the problem is length is a long and BeginRead only accepts int, if the file is to big it'll probably overflow. an other way i was thinking was read it by smaller chunks but every time i have to read a new chunk of bytes i'll have to create a new array (just wanted to avoid having to initialize new and bigger arrays).
If anyone knows any better way or simpler i'd be 开发者_如何学JAVAhappy and grateful :P other wise i'll do it with the reading in smaller chunks. Ty for any help.
You can chunk it into a MemoryStream (the MemoryStream will manage appending the binary information in memory) and at the end you can just call memoryStream.ToArray().
Also, here is a way to copy between two stream instances (from your file stream to your MemorySream:
How do I copy the contents of one stream to another?
You'll have to read it by chunks anyway since .NET doesn't support objects larger than 2Gb.
Another way to do it would be to just spin up a thread and call System.IO.File.ReadAllBytes(string). It doesn't sound like there's any advantage to chunking (because you're going to bring the whole thing into memory) so this would be pretty straightforward.
With some help from this sample:
private void GetTheFile()
{
FileFetcher fileFetcher = new FileFetcher(Fetch);
fileFetcher.BeginInvoke(@"c:\test.yap", new AsyncCallback(AfterFetch), null);
}
private void AfterFetch(IAsyncResult result)
{
AsyncResult async = (AsyncResult) result;
FileFetcher fetcher = (FileFetcher)async.AsyncDelegate;
byte[] file = fetcher.EndInvoke(result);
//Do whatever you want with the file
MessageBox.Show(file.Length.ToString());
}
public byte[] Fetch(string filename)
{
return File.ReadAllBytes(filename);
}
You can specify an offset
in your array which will allow you to allocate a single big array.
public IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, Object state)
stream.BeginRead(buffer, totalRead, chunkSize, ...);
Then on the EndRead, add the read size to totalRead
精彩评论