Embed a Word Document in C#

前端 未结 3 1356
余生分开走
余生分开走 2021-01-16 04:25

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 ne

相关标签:
3条回答
  • 2021-01-16 04:45

    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);
         }
    }
    
    0 讨论(0)
  • 2021-01-16 04:56

    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 讨论(0)
  • 2021-01-16 05:00

    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.

    0 讨论(0)
提交回复
热议问题