开发者

Embed a Word Document in C#

开发者 https://www.devze.com 2023-01-29 06:16 出处:网络
I want to open a MS Word document from my program.At the moment, it can find it when in designer mode but when i publish my program it can\'t find the file. I believe I need to embed it into my progra

I want to open a MS Word document from my program. At the moment, it can find it when in designer mode but when i publish my program it can't find the file. I believe I need to embed it into my program but I don't know how to do this. This is my current code to open the docu开发者_开发知识库ment:

System.Diagnostics.Process.Start("Manual.docx");

I think the Word document needs to be embedded into the resources of the .exe but i don't know how to to do this.

Can anyone help with some suggestions?


Aaron is pretty right on adding an embedded resource. Do the following to access an embedded resource:

Assembly thisAssembly;
thisAssembly = Assembly.GetExecutingAssembly();
Stream someStream;
someStream = thisAssembly.GetManifestResourceStream("Namespace.Resources.FilenameWithExt");

More info here: How to embed and access resources by using Visual C#

Edit: Now to actually run the file you will need to copy the file in some temp dir. You can use the following function to save the stream.

public void SaveStreamToFile(string fileFullPath, Stream stream)
{
    if (stream.Length == 0) return;

    // Create a FileStream object to write a stream to a file
    using (FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length))
    {
        // Fill the bytes[] array with the stream data
        byte[] bytesInStream = new byte[stream.Length];
        stream.Read(bytesInStream, 0, (int)bytesInStream.Length);

        // Use FileStream object to write to the specified file
        fileStream.Write(bytesInStream, 0, bytesInStream.Length);
     }
}


Right click the folder where you want to store the file within the Solution and choose Add -> Existing Item.

Once you add the file you can change the Build Action of the file within your project to be an Embedded Resource, versus a Resource. This can be done by going to the Properties within VS of the file and modifying the Build Action property.


Just include it to your project (add existing item) and from the menu that opens, select all files and select your word document. Also Copy the document into your Bin/Debug folder. If you are using an installer, include the document in the installer and it should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消