简体   繁体   English

如何在c#中添加或使用.docx模板文件作为资源或参考?

[英]How to add or use .docx template file as a resource or reference in c#?

Im trying to make a winapp that fills the document template file using the C# form and create a new .docx file. 我试图制作一个使用C#表单填充文档模板文件的winapp,并创建一个新的.docx文件。 Where should i put the .docx file and how should i use it. .docx文件应该放在哪里以及如何使用。 I placed my template inside the Debug folder and load it like: 我将模板放在Debug文件夹中,并按以下方式加载:

dox.LoadFromFile("template.docx");

Im having a problem when using the executable because it doesnt seem to find the template.docx 我在使用可执行文件时遇到问题,因为它似乎找不到template.docx

It is possibly to have files copies into the Output Directory. 可能会将文件复制到输出目录中。 This is a simple mater of setting the File up accordingly . 这是一个设置文件了一个简单的母校相应

However, having data like this in the Programm directory is frowned upon. 但是,在Programm目录中拥有像这样的数据是令人讨厌的。 As of Windows XP, you are unlikely to get write access to those files anymore. 从Windows XP开始,您不太可能再获得对这些文件的写权限。 So any form of changes would be blocked unless your programm runs with full Administrative Rights. 因此,除非您的程序以完全的管理权限运行,否则任何形式的更改都将被阻止。

The intended place for such files are the SpecialFolders . 此类文件的预期位置是SpecialFolders On those you are guaranteed write rights to some degree. 在那些方面,可以保证您在某种程度上拥有写权。 While you could still store the template in the programm directory to copy it there if needed, it might be better to use copy it to default user as part of hte setup process. 虽然您仍可以将模板存储在programm目录中,以便在需要时将其复制到那里,但最好将其复制到默认用户作为设置过程的一部分。

Of course Visual Studio loves to run code under rather odd user accounts. 当然,Visual Studio喜欢在相当奇怪的用户帐户下运行代码。 So I am not sure how far that works for testing. 因此,我不确定测试的有效程度。

You can store you word document directly in your assembly (juste copy past the file in your project). 您可以将Word文档直接存储在程序集中(只需复制过去的文件到项目中即可)。

Then you just copy it to windows temp folder before doing your own business. 然后,您可以在进行自己的业务之前将其复制到Windows temp文件夹。 Just don't forget to delete the file in the temp folder when you are good because windows won't do it for you. 只是别忘了在您状况良好时删除temp文件夹中的文件,因为Windows不会帮您删除它。

    Dim fileLocation As String = Path.GetTempFileName()
    Using newFile As Stream = New FileStream(fileLocation, FileMode.Create)
         Assembly.GetExecutingAssembly().GetManifestResourceStream("YourAssemblyName.yourfile.docx").CopyTo(newFile)
    End Using 

    ...
    System.IO.File.Delete(fileLocation)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM