Reputation: 11100
I use OpenFileDialog to search for a specific file. 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?
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.
Upvotes: 1
Views: 1074
Reputation: 11415
On 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);
Upvotes: 4
Reputation: 24723
This will retrieve your path based on the FileName
property of the OpenFileDialog
.
String path = System.IO.Path.GetDirectoryName(OpenFileDialog.FileName);
Upvotes: 1
Reputation:
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()
Upvotes: 1
Reputation: 19130
Instead of copy pasting answers from MSDN I'll just link to them.
MSDN documentation on Forms OpenFileDialog.
MSDN documentaiton on WPF OpenFileDialog.
Please try to look for a answer before posting questions.
Upvotes: 1
Reputation: 1127
Try FileName. Or FileNames if you allow multiple files to be selected(Multiselect=true)
Upvotes: 0
Reputation: 191037
If you are using WinForms, use the FileName
property of your OpenFileDialog
instance.
Upvotes: 5
Reputation: 17808
After the dialog closes there should be a file path (or something similar) property on the OpenFileDialog object, it will store whatever file path the user entered.
Upvotes: 0