我如何安全地从在asp.net流中读取? [英] How do I safely read from a stream in asp.net?

查看:103
本文介绍了我如何安全地从在asp.net流中读取?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

如果

从单一的通话读取一个流阅读是非常危险的。你假设所有的数据将被提供立即,这并非总是如此。你应该总是循环轮,直到看完有没有更多的数据。

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.

我应该如何改变上述code,使它变得不那么危险?

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

推荐答案

乔恩斯基特实际上有一个非常好的博客文章有关的所有不同的方式,人们尝试读取数据流,为什么每一个被打破(它与他认为是结束是理想的解决方案):

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):

在C#读二进制数据

这篇关于我如何安全地从在asp.net流中读取?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆