我遇到了一个问题,我正在开发一个 WPF 应用程序,其中有一个名为“帮助”的页面,其中有一个按钮 go 当用户单击此按钮时,我必须向用户提供帮助文件夹中的 pdf 文件。 现在我的问题是如果我这样写路径
**string pdfurl1 = ((@"D:\addnkit\projects\wdine\widdne_working\Wdine Us\Wddine\Wine\Help\Emerald Wine Dispensing Software.pdf"));
System.Diagnostics.Process.Start(pdfurl1);**
工作顺利
但我知道这在其他电脑上不起作用,所以我想知道如何编写可以在任何电脑上运行的相同代码
我也试过这样
(@"pack://application:,,,/Widne;component/help/mypdf.pdf"
但是它不起作用
[更新]
我已经尝试了所有的解决方案,但仍然不起作用,我不知道为什么? 请再检查一次 Widne >> 帮助 >> mypdf
使用你的exe的路径
System.AppDomain.CurrentDomain.BaseDirectory
string path = System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)
+ "\\Widne\\component\\help\\mypdf.pdf";
System.Diagnostics.Process.Start(path )
更新:
在打开文件之前,他必须已存在,在这种情况下,您可以将属性设置为 PDF 文件
Copy to Output Directory
至 Copy always
第二种方法
packuri
是你应该使用的。
您的问题很可能是您的
mypdf.pdf
需要在 Visual Studio 中更改其属性,以便它在构建时实际复制 pdf 文件,而不是嵌入到应用程序中,从而阻止最终用户读取 pdf 文件。
在 pdf 文件上设置这些属性并重建应用程序
构建行动:内容
复制到输出目录:始终复制
编辑:查看这个答案以获取构建操作的解释。
Diagnostics.Process
类与WPF无关。如果路径是相对于您的应用程序的,则可以使用相对路径。如果您担心应用程序运行的工作目录与程序集存储的目录不同,您可以使用 查询该程序集的原始文件夹
Assembly.GetExecutingAssembly().CodeBase
并使用
Path.Combine
构建 PDF 的路径。
您可以使用相对路径:
./ - start at the .exe directory
../ - go up one folder from the .exe
../../ - go up two folders etc.
编辑:
假设您的 .exe 在 bin 文件夹中:
**string pdfurl1 = ((@"..\Help\Emerald Wine Dispensing Software.pdf"));
System.Diagnostics.Process.Start(pdfurl1);**
您可以使用
Directory.GetCurrentDirectory()
。这将为您提供启动应用程序的目录。因此,如果您将文件放置在启动应用程序的位置,它将是这样的:
string pdfurl1 = ((Directory.GetCurrentDirectory() + "\Emerald Wine Dispensing Software.pdf"));
System.Diagnostics.Process.Start(pdfurl1);
对于目录对话框获取目录路径,首先添加引用System.Windows.Forms,然后解析,然后将此代码放在单击按钮中。
var dialog = new FolderBrowserDialog();
dialog.ShowDialog();
folderpathTB.Text = dialog.SelectedPath;
(folderpathTB 是我想要放置文件夹路径的 TextBox 的名称,或者您也可以将其分配给字符串变量,即)
string folder = dialog.SelectedPath;
如果您想获取文件名/路径,只需单击按钮即可完成此操作
FileDialog fileDialog = new OpenFileDialog();
fileDialog.ShowDialog();
folderpathTB.Text = fileDialog.FileName;
(folderpathTB 是我想要放置文件路径的 TextBox 的名称,或者您也可以将其分配给字符串变量)
注意:对于文件夹对话框,必须将System.Windows.Forms.dll添加到项目中,否则无法工作。
您也可以尝试使用此代码:
string pdfFolder;
#if DEBUG
DirectoryInfo directoryInfo = Directory.GetParent(Directory.GetParent(Environment.CurrentDirectory).FullName);
pdfFolder = directoryInfo.FullName + @"\PdfFile\Auto Refill Reminder List.pdf";
System.Diagnostics.Process.Start(pdfFolder );
#endif
#if (!DEBUG)
pdfFolder = Environment.CurrentDirectory + @"\PdfFile\Auto Refill Reminder List.pdf";
Process.Start(pdfFolder);
#endif
并更改内容的构建类型:
现在 2024 年:
var folderDialog = new OpenFolderDialog
{
Title = "Select Folder",
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86)
};
if (folderDialog.ShowDialog() == true)
{
var folderName = folderDialog.FolderName;
MessageBox.Show($"You picked ${folderName}!");
}
来源:https://devblogs.microsoft.com/dotnet/wpf-file-dialog-improvements-in-dotnet-8/