Embed a Word Document in C#

前端 未结 3 1382
余生分开走
余生分开走 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);
         }
    }
    

提交回复
热议问题