J M R
J M R

Reputation: 3

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. Where should i put the .docx file and how should i use it. I placed my template inside the Debug folder and load it like:

dox.LoadFromFile("template.docx");

Im having a problem when using the executable because it doesnt seem to find the template.docx

Upvotes: 0

Views: 519

Answers (2)

Marco Guignard
Marco Guignard

Reputation: 653

You can store you word document directly in your assembly (juste copy past the file in your project).

Then you just copy it to windows temp folder before doing your own business. Just don't forget to delete the file in the temp folder when you are good because windows won't do it for you.

    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)

Upvotes: 0

Christopher
Christopher

Reputation: 9804

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. As of Windows XP, you are unlikely to get write access to those files anymore. 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. 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.

Of course Visual Studio loves to run code under rather odd user accounts. So I am not sure how far that works for testing.

Upvotes: 1

Related Questions