用c#加载外部文件(从资源文件夹)



我有一个PDF文件,我想加载一个按钮点击。我可以在调试模式下引用文件,但是当我发布项目时,pdf不会迁移或"安装"项目。

文件位于Resources/file.pdf

在WPF表单中,我调用"OpenFile_Click"点击功能

下面是我的函数:

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

这显然不能打开那个文件。我可以在Resources文件夹前添加../../,它将在调试中打开,但这不是很有帮助。

那么,打开像PDF这样的外部文件的最佳选择是什么?

在按照Clemens的建议设置PropertiesCopy to Output Directory=Copy if Newer之后,我还建议使用System.IO.Path.Combine,以确保平台使用正确的路径分隔符。

如果在调用Process.Start时仍然有错误,那么尝试启动"explorer.exe"使用合并后的文件名。我成功地测试了下面的代码,看看是否可以复制。

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);
}

最新更新