【发布时间】:2011-02-09 15:06:21
【问题描述】:
我使用 OpenFileDialog 来搜索特定文件。当用户选择文件时,我想将该路径存储在变量中。但是,这些似乎不是 OpenFileDialog 中的选项?
有人知道怎么做吗?
谢谢。
编辑:这是 Winforms,我不想保存包含文件名的路径,只保存文件所在的位置。
【问题讨论】:
标签: c# winforms openfiledialog
我使用 OpenFileDialog 来搜索特定文件。当用户选择文件时,我想将该路径存储在变量中。但是,这些似乎不是 OpenFileDialog 中的选项?
有人知道怎么做吗?
谢谢。
编辑:这是 Winforms,我不想保存包含文件名的路径,只保存文件所在的位置。
【问题讨论】:
标签: c# winforms openfiledialog
如果您使用的是 WinForms,请使用您的 OpenFileDialog 实例的 FileName 属性。
【讨论】:
在 WinForms 上:
String fileName;
OpenFileDialog ofd = new OpenFileDialog();
DialogResult dr = ofd.ShowDialog();
if (dr == DialogResult.Ok) {
fileName = ofd.FileName;
}
//getting only the path:
String path = fileName.Substring(0, fileName.LastIndexOf('\\'));
//or easier (thanks to Aaron)
String path = System.IO.Path.GetDirectoryName(fileName);
【讨论】:
这将根据OpenFileDialog 的FileName 属性检索您的路径。
String path = System.IO.Path.GetDirectoryName(OpenFileDialog.FileName);
【讨论】:
我不会从 MSDN 复制粘贴答案,而是直接链接到它们。
Forms OpenFileDialog 上的 MSDN 文档。
WPF OpenFileDialog 上的 MSDN 文档。
请在发布问题之前尝试寻找答案。
【讨论】:
您将路径存储在其他地方!
我通常做的是创建一个用户范围的配置变量。
以下是它的使用示例:
var filename = Properties.Settings.Default.LastDocument;
var sfd = new Microsoft.Win32.SaveFileDialog();
sfd.FileName = filename;
/* configure SFD */
var result = sfd.ShowDialog() ?? false;
if (!result)
return;
/* save stuff here */
Properties.Settings.Default.LastDocument = filename;
Properties.Settings.Default.Save();
要仅保存目录,请使用System.IO.Path.GetDirectoryName()
【讨论】:
对话框关闭后,OpenFileDialog 对象上应该有一个文件路径(或类似的东西)属性,它将存储用户输入的任何文件路径。
【讨论】:
试试文件名。如果您允许选择多个文件,则为 FileNames(Multiselect=true)
【讨论】: