C# 如何将字节[]转换为互操作对象的Word(转换为Word文档)?
我想在数据库中保存word文档,我是这样做的:C# 如何将字节[]转换为互操作对象的Word(转换为Word文档)?,c#,stream,office-interop,C#,Stream,Office Interop,我想在数据库中保存word文档,我是这样做的: FileStream st = new FileStream(filePath, FileMode.Open); byte[] buffer = new byte[st.Length]; st.Read(buffer, 0, (int)st.Length); st.Close(); //save Buffer into DB //myentityobject.FileContent = buffer; //save it
FileStream st = new FileStream(filePath, FileMode.Open);
byte[] buffer = new byte[st.Length];
st.Read(buffer, 0, (int)st.Length);
st.Close();
//save Buffer into DB
//myentityobject.FileContent = buffer;
//save it
但是当我想阅读它时,我不知道如何从我从DB获得的流中生成word文档。我尝试了以下方法:
var doc = myentityobject.FileContent;
MemoryStream stream = new MemoryStream(doc as byte[]);
letterPatternDoc = new Document(stream);
filePath = @"D:\LetterPatternDocument001.doc";
object oMissing = System.Reflection.Missing.Value;
currentApp = new wd.Application();
currentApp.Visible = true;
currentDoc = currentApp.Documents.Add(Type.Missing, Type.Missing);
currentDoc = doc;
currentDoc.SaveAs(ref path, oMissing, oMissing, oMissing, oMissing, oMissing, false
, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing, oMissing);
但它不起作用
编辑:
我修改了代码,现在可以工作了,我用filestream保存了文件,然后读了一遍。但我不知道这是一个好的解决方案吗
FileStream fileSream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite);
BinaryWriter bw = new BinaryWriter(fileSream);
bw.Write(FileContent);//filecontent is a byte[]
fileSream.Close();
// WordDoc.OpenDocument(filePath);
你能试试这个方法吗
将文件保存到某个位置,并将文件路径保存到数据库。当您要读取此文件时,可以从数据库获取文件路径。希望它能帮助您:)尝试序列化文档对象,从而保留文档的状态并将其保存到数据库中。在读取反序列化时,您将再次可以显示文档对象。word无法打开流,但您可以保存它,修改它,然后在数据库中更新后,只需删除此“临时”file如果不想使用FileStream,还可以利用
System.IO.file
命名空间中内置的writealBytes静态方法
下面是一个简单的示例(假设安装并引用了Interop.Word):
有关此主题的更多信息,请访问我的博客。详细说明“不起作用”。。。它做什么(或不做什么)@psubsee2003:正如我所说,我在数据库中保存了一个word文档,现在我想在word应用程序中读取并显示它。什么是bw.Write(ViewSource.CurrentItem.letternPatternDocument.FileContent);那是你自己的观众吗?
// byte[] fileBytes = getFileBytesFromDB();
var tmpFile = Path.GetTempFileName();
File.WriteAllBytes(tmpFile, fileBytes);
Application app = new word.Application();
Document doc = app.Documents.Open(filePath);
// do your stuff
// convert the DOCX file back to a Byte Array
doc.Close();
app.Quit(); // VERY IMPORTANT: do this to close the MS Word instance
byte[] newFileBytes= File.ReadAllBytes(tmpFile);
File.Delete(tmpFile);