[英]C# FilePath Help
I use OpenFileDialog to search for a specific file. 我使用OpenFileDialog搜索特定文件。 When the user chooses the file, I want to store that path in a variable.
当用户选择文件时,我想将该路径存储在变量中。 However, these doesn't seem to be an option for this within OpenFileDialog?
但是,这些似乎不是OpenFileDialog中的选项吗?
Does anybody know how to do this? 有人知道怎么做这个吗?
Thanks. 谢谢。
Edit: This is Winforms, and I don't want to save the path inclusive of the filename, just the location where the file is. 编辑:这是Winforms,我不想保存包含文件名的路径,而只保存文件所在的位置。
如果使用的是WinForms,请使用OpenFileDialog
实例的FileName
属性。
On WinForms: 在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);
Instead of copy pasting answers from MSDN I'll just link to them. 而不是从MSDN复制粘贴答案,而是直接链接到它们。
MSDN documentation on Forms OpenFileDialog . 表单OpenFileDialog上的MSDN文档。
MSDN documentaiton on WPF OpenFileDialog . 在WPF OpenFileDialog上的MSDN文档。
Please try to look for a answer before posting questions. 在发布问题之前,请尝试寻找答案。
You store the path ... somewhere else! 您将路径存储在其他地方!
What I usually do is create a user-scoped configuration variable. 我通常要做的是创建一个用户范围的配置变量。
Here's a sample of its use: 以下是其用法示例:
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();
To save just the directory, use System.IO.Path.GetDirectoryName() 要仅保存目录,请使用System.IO.Path.GetDirectoryName()
这将基于OpenFileDialog
的FileName
属性检索路径。
String path = System.IO.Path.GetDirectoryName(OpenFileDialog.FileName);
对话框关闭后,OpenFileDialog对象上应有一个文件路径(或类似内容)属性,它将存储用户输入的任何文件路径。
Try FileName. 尝试使用FileName。 Or FileNames if you allow multiple files to be selected(Multiselect=true)
如果允许选择多个文件,则为FileNames(Multiselect = true)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.