tags:

views:

289

answers:

2

I'm distributing an application via ClickOnce (runs 'online' from network'), included in the app are a couple of text files which are copied to the deployment location correctly when published.

I'm attempting to refer to the path of these files programatically:

Dim t As New HTMLTemplate("ReportTemplates\IncidentDetailMain.txt")

Sometimes this works, sometimes the app seems to look in the users My Documents folder, resulting in a DirectoryNotFoundException.

Can anyone explain what is going on here?

+1  A: 

The safest way to do this is by getting the path of your exe and then using that as the base.

You can do this by using the following location , System.Environment.CurrentDirectory

RC1140
Thanks, it still seems to work, I'll wait and see if the errors reoccur.
Simon
Yes, problem re-occurs intermittently, I'm hoping @andhammar's answer below will resolve.
Simon
+1  A: 

The best way is to use

System.Windows.Forms.Application.StartupPath

which will give you the uri to the folder where the executable of the application is. You can then use that reference files that in your case always should be in the same relative path to the executable.

MSDN: Application.StartupPath

This can be used both for WinForms and WPF apps.

System.Environment.CurrentDirectory may change during the lifetime of the app if you let the user open/save files etc. - so the StartupPath is safer.

So, your final code would be:

string filePath = Path.Combine(
    System.Windows.Forms.Application.StartupPath,
    "ReportTemplates\IncidentDetailMain.txt");
.. = new HTMLTemplate(filePath);
andyhammar