首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SqlFileStream写错误?

SqlFileStream写错误?
EN

Stack Overflow用户
提问于 2010-08-20 16:28:32
回答 2查看 664关注 0票数 0

几个月来,我一直在为Server 2008 FileStream编写和阅读PDF文件,没有任何重大问题(除了繁琐的用户权限)。昨天,我让一个用户告诉我,他们的一些PDF被写入FileStream后被破坏了。所以,我做了一些调试,发现了这个问题,但似乎是SqlFileStream库将文件写入FileStream的bug。

下面是我写到FileStream的代码:

代码语言:javascript
复制
// Byte array representing the FileStream
byte[] fsBytes = (byte[])obj;

SqlFileStream sqlFS = new SqlFileStream(path, fsBytes, FileAccess.Write);

byte[] b = new byte[4096];
int read;

stream.Seek(0, SeekOrigin.Begin);

while ((read = stream.Read(b, 0, b.Length)) > 0) {
    sqlFS.Write(b, 0, read);
}

sqlFS.Close();

通过调试,我确定从流中读取的最后一次迭代的读取值等于1253,这意味着最后一次读取的字节数组中有从索引0到1252,的数据,这是正确的。1253年前后的一切都是从上一次阅读开始的。

因此,我的理解是,sqlFS.Write(b,0,1253)将将字节数组的索引0到1252写入SqlFileStream。但是,它实际上是将字节数组中的everything写入SqlFileStream。我已经通过从数据库中提取PDF来验证这一点,即使我不能正常地查看它,因为它现在已经损坏了,我仍然可以在文本编辑器中打开它,并在它的末尾查看不属于那里的garbal (所有位于1253位置及之后的数据)。

我在这里做错了什么,或者SqlFileStream写方法有一个bug,就像我想的那样?

奇怪的是,我上传了很多其他PDF文件和文本文件和图像,而我从未见过这个问题。我不知道为什么会有PDF而不是其他的.

编辑:这里是我的read方法的代码。bug也可能出现在这里(感谢Remus指出了这一点!)

代码语言:javascript
复制
SqlFileStream objSqlFileStream = new SqlFileStream(path, objContext, FileAccess.Read);
objSqlFileStream.Seek(0, SeekOrigin.Begin);

b = new byte[4096];
int read;

while ((read = objSqlFileStream.Read(b, 0, b.Length)) > 0) {
   Response.BinaryWrite(b);
}

objSqlFileStream.Close();

编辑#2 (固定代码):

代码语言:javascript
复制
SqlFileStream objSqlFileStream = new SqlFileStream(path, objContext, FileAccess.Read);
objSqlFileStream.Seek(0, SeekOrigin.Begin);

b = new byte[4096];
int read;

while ((read = objSqlFileStream.Read(b, 0, b.Length)) > 0) {
    if (read < 4096) {
        byte[] b2 = new byte[read];
        System.Buffer.BlockCopy(b, 0, b2, 0, read);
        Response.BinaryWrite(b2);
    }
    else
        Response.BinaryWrite(b);
}

objSqlFileStream.Close();
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-08-20 17:14:19

代码语言:javascript
复制
while ((read = objSqlFileStream.Read(b, 0, b.Length)) > 0) {
   Response.BinaryWrite(b);
}

这将写入整个原始byte[]数组b,并忽略大小read。令人震惊的是HttpResponse没有签名.BinaryWrite(byte[], offset, size)..。恐怕在写出来之前你得先写b.Resize(read);

票数 2
EN

Stack Overflow用户

发布于 2010-08-20 16:32:35

写入后清除字节数组有帮助吗?

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3532856

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档