c# - FileStream returns Length = 0 -
i'm trying read local file , upload on ftp server. when read image file, ok, when read doc or docx file, filestream returns length = 0. here code: checked other files, appears works fine images , returns 0 other file
if (!ftpclient.fileexists(filename)) { try { ftpclient.validatecertificate += (control, e) => { e.accept = true; }; const int buffer_size = 64 * 1024; // 64kb buffer byte[] buffer = new byte[buffer_size]; using (stream readstream = new filestream(tempfilepath, filemode.open, fileaccess.read)) using (stream writestream = ftpclient.openwrite(filename)) { while (readstream.position < readstream.length) { buffer.initialize(); int bytesread = readstream.read(buffer, 0, buffer_size); writestream.write(buffer, 0, bytesread); } readstream.flush(); readstream.close(); writestream.flush(); writestream.close(); deletetempfile(tempfilepath); return true; } } catch (exception ex) { return false; } }
i couldn't find whats wrong it. please me?
while doesn't answer specific question, don't need know length of stream. keep reading until hit 0 length read. a 0 byte read guaranteed indicate the end of stream.
return value
type: system.int32
the total number of bytes read buffer. can less number of bytes requested if many bytes not available, or 0 (0) if end of stream has been reached.
while (true) { int bytesread = readstream.read(buffer, 0, buffer_size); if(bytesread==0) { break; } writestream.write(buffer, 0, bytesread); }
alternatively:
readstream.copyto(writestream);
is concise method of stating goal...
Comments
Post a Comment