How do I safely read from a stream in asp.net?

你说的曾经没有我的故事 提交于 2020-01-05 09:21:51

问题


byte[] bytes = new byte[uploader.UploadedFiles[0].InputStream.Length];
uploader.UploadedFiles[0].InputStream.Read(bytes, 0, bytes.Length);

var storedFile = new document();
string strFullPath = uploader.UploadedFiles[0].FileName;
string strFileName = Path.GetFileName(strFullPath);

storedFile.document_id = Guid.NewGuid();
storedFile.content_type = uploader.UploadedFiles[0].ContentType;
storedFile.original_name = strFileName;
storedFile.file_data = bytes;
storedFile.date_created = DateTime.Now;
db.documents.InsertOnSubmit(storedFile);
db.SubmitChanges();

If:

Reading from a stream in a single call to Read is very dangerous. You're assuming all the data will be made available immediately, which isn't always the case. You should always loop round, reading until there's no more data.

How should I change the above code to make it 'less dangerous'?


回答1:


Jon Skeet actually has a really good blog post about all the different ways that people try to read Streams and why each one is broken (it ends with what he believes is the ideal solution):

Reading binary data in C#



来源:https://stackoverflow.com/questions/4155844/how-do-i-safely-read-from-a-stream-in-asp-net

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