Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

c# - How to create Microsoft.Office.Interop.Word.Document object from byte array, without saving it to disk?

How can I create a Microsoft.Office.Interop.Word.Document object from byte array, without saving it to disk using C#?

public static int GetCounterOfCharacter(byte[] wordContent)
{
   Application objWord = new Application();
   Microsoft.Office.Interop.Word.Document objDoc = new Document();
   //objDoc = objWord.Documents.Open(("D:/Test.docx"); i want to create document from byte array "wordContent"
   return  objDoc.Characters.Count;      
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no straight-forward way of doing this as far as I know. The Word interop libs are not able to read from a byte stream. Unless you are working with huge (or a huge amount of) files, I would recommend simply using a tmp file:

Application app = new Application();

byte[] wordContent = GetBytesInSomeWay();

var tmpFile = Path.GetTempFileName();
var tmpFileStream = File.OpenWrite(tmpFile);
tmpFileStream.Write(wordContent, 0, wordContent.Length);
tmpFileStream.Close();

app.Documents.Open(tmpFile);

I know this isn't the answer you're looking for, but in a case like this (where doing what you really want to do requires quite a bit of time and fidgeting) it might be worth considering whether or not development time outweighs runtime performance.

If you still want to look into a way to solve it the way you intend it to, I'd recommend the answers in this thread.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...