Skip to main content
Home Forums Silverlight Programming Programming with .NET - General OpenFileDialog - reading the filestream
4 replies. Latest Post by ivanpelly on November 5, 2009.
(0)
ivanpelly
Member
18 points
27 Posts
11-04-2009 12:57 PM |
I'm creating an app that uploads potentially large files to a server. I'd like to read the file a piece at a time, and upload those pieces. The user selects the file using the OpenFileDialog. I'm finding that OpenFiledDialog.File.OpenRead.Read() always starts reading at the beginning of the filestream, regardless of whether any data has already been read, and using OpenFiledDialog.File.OpenRead.Position and OpenFiledDialog.File.OpenRead.Seek don't seem to have any effect - reading always starts at the beginning of the file. Is this for real? If so, am I forced to load the entire 100MB file into memory before I can do anything with it? What am I missing here? Thanks in advance
Sergey.L...
Contributor
7256 points
1,354 Posts
11-04-2009 1:29 PM |
Hi Ivan,
Can you show a code for read bytes from file?
sladapter
All-Star
17445 points
3,173 Posts
11-04-2009 2:16 PM |
If you need to read the file one chunk at a time, here is the code how you do it:
const int CHUNKSIZE = 40000; // You can change this number
OpenFileDialog d = new OpenFileDialog();if (d.ShowDialog() == true){ FileInfo f =d.File;
Stream s = f.OpenRead();
int chunkSize; while (s.Position > -1 && s.Position < s.Length) { if (s.Length - s.Position >= CHUNKSIZE) chunkSize = CHUNKSIZE; else chunkSize = (int)(s.Length - s.Position); // last chunk byte[] fileBytes = new byte[chunkSize]; int byteCount = s.Read(fileBytes, 0, chunkSize); //Read the bytes in chunk, read will start from the end position of last read
// now you can deal with your bytes array fileBytes }
}
11-04-2009 2:35 PM |
Thanks for the responses. My code is very similar to sladapter's, except I didn't take the extra step of assigning OpenFileDialog.File.OpenRead to a Stream object - I was calling OpenRead's methods directly. Not sure why, but when I assign OpenFileDialog.File.OpenReadto a Stream object, and read via that, everything works (i.e. I can set the position in the Stream object, etc.) Thanks for the guidance!
11-05-2009 11:01 AM |
After digging a little deeper, I figured out what was going on. Each call to OpenFileDialog.File.OpenRead doesn't return the filestream to the underlying file; it returns a new, different filestream each time you call it. So, where I was doing something like:
ofd.File.OpenRead.Read(bytes,0,bytesToRead) ...ofd.File.OpenRead.Read(bytes,0,bytesToRead) ' <-- This line would be reading from a new filestream, starting as position 0