Will Roberts
Will Roberts

Reputation: 69

Load External Files with C# (From Resource Folder)

I have a PDF file that I would like to load with a button click. I can reference the file in debug mode, but when I publish the project, the pdf doesn't migrate over or 'install' with the project.

The file is located in Resources/file.pdf

In the WPF form, I call the "OpenFile_Click" function on click.

Here is my function:

private void OpenFile_Click(object sender, RoutedEventArgs e) 
{
  string appPath = AppDomain.CurrentDomain.BaseDirectory;
  Process.Start(appPath + "Resources/file.pdf");
}

This clearly doesn't work to open that file. I can add ../../ in front of the Resources folder and it will open in debug, but that isn't very helpful.

So, what is the best option for opening an external file like a PDF?

Upvotes: 0

Views: 606

Answers (1)

IV.
IV.

Reputation: 9463

After setting Properties\Copy to Output Directory = Copy if Newer as suggested by Clemens, I would also recommend the use of System.IO.Path.Combine to ensure the correct path delimiter for the platform.

If there is still an error when invoking the Process.Start then try starting "explorer.exe" with the combined file name. I successfully tested the following, see if you can repro.

private void OpenFile_Click(object sender, RoutedEventArgs e)
{
    var filePath = System.IO.Path.Combine(
        AppDomain.CurrentDomain.BaseDirectory,
        "Resources",
        "file.pdf"
    );

    Process.Start("explorer.exe", filePath);
}

Upvotes: 1

Related Questions