Darren Young
Darren Young

Reputation: 11100

C# FilePath Help

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

Answers (7)

oopbase
oopbase

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

Aaron McIver
Aaron McIver

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

user1228
user1228

Reputation:

You store the path ... somewhere else!

What I usually do is create a user-scoped configuration variable.

enter image description here

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

Steven Jeuris
Steven Jeuris

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

chhenni
chhenni

Reputation: 1127

Try FileName. Or FileNames if you allow multiple files to be selected(Multiselect=true)

Upvotes: 0

Daniel A. White
Daniel A. White

Reputation: 191037

If you are using WinForms, use the FileName property of your OpenFileDialog instance.

Upvotes: 5

asawyer
asawyer

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

Related Questions