使用 MemoryStream 保存 .docx 文件 C#
我在将文件从内存流上传到数据库时遇到一些麻烦(它在数据库中显示为 0x,所以我猜它没有正确保存)。我不确定创建流是否有问题,或者从流保存到数据库是否应该以不同的方式完成。
private void test {
byte[] storage = new byte[500000];
using (MemoryStream stream = new MemoryStream(storage))
DocX documentWord = DocX.Create(stream);
// some stuff
documentWord.Save();
databaseFilePut(stream);
}
public static void databaseFilePut(MemoryStream stream) {
byte[] file;
using (var reader = new BinaryReader(stream)) {
file = reader.ReadBytes((int) stream.Length);
// reader.Close();
}
//stream.Close();
//}
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetailsDZP))
using (var sqlWrite = new SqlCommand("INSERT INTO Raporty (RaportPlik) Values(@File)", varConnection)) {
sqlWrite.Parameters.Add("@File", SqlDbType.VarBinary, file.Length).Value = file;
sqlWrite.ExecuteNonQuery();
}
}
我做错了什么?我正在使用 Docx codeplex 库。
I've some trouble to upload file from Memory Stream to database (it's visible in DB as 0x so i guess it doesn't get saved properly). I am not sure whether it's a problem with Stream being created or save to db from stream should be done differently.
private void test {
byte[] storage = new byte[500000];
using (MemoryStream stream = new MemoryStream(storage))
DocX documentWord = DocX.Create(stream);
// some stuff
documentWord.Save();
databaseFilePut(stream);
}
public static void databaseFilePut(MemoryStream stream) {
byte[] file;
using (var reader = new BinaryReader(stream)) {
file = reader.ReadBytes((int) stream.Length);
// reader.Close();
}
//stream.Close();
//}
using (var varConnection = Locale.sqlConnectOneTime(Locale.sqlDataConnectionDetailsDZP))
using (var sqlWrite = new SqlCommand("INSERT INTO Raporty (RaportPlik) Values(@File)", varConnection)) {
sqlWrite.Parameters.Add("@File", SqlDbType.VarBinary, file.Length).Value = file;
sqlWrite.ExecuteNonQuery();
}
}
What am i doing wrong? I am using Docx codeplex library.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在写入流,然后立即尝试从中读取而不回退...因此没有数据可供读取。
幸运的是,无论如何,有一种非常简单的方法可以简化代码:
但是,您还有另一个潜在的问题:
这将使
MemoryStream
的固定大小为 500K - 不更多,不少。我怀疑这不是你想要的;我建议您删除storage
变量,只调用无参数MemoryStream
构造函数。You're writing to the stream and then immediately trying to read from it without rewinding... so there's no data to read.
Fortunately, there's a very easy way of simplifying the code anyway:
However, you've got another potential problem:
This will make the
MemoryStream
have a fixed size of 500K - no more, no less. I suspect that's not what you want; I suggest you get rid of thestorage
variable and just call the parameterlessMemoryStream
constructor.