jrdnoland
jrdnoland

Reputation: 115

Get complete file path from file click in File Explorer

Using Visual Studio 2017 and Windows 10 I want to be able to open a file explorer and navigate to a file outside of the program. Once my file is collected I want to get the file path and the complete file name for the file explorer.

        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.Filter = "All files (*.*)|*.*";
        if (openFileDialog1.ShowDialog() == DialogResult.OK)  
            textBoxFolderpath.Text= openFileDialog1.FileName;
        if (textBoxFolderpath.Text.Contains('\\'))
            textBoxFolderpath.Text = textBoxFolderpath.Text.Substring(0, textBoxFolderpath.Text.LastIndexOf('\\'));  

This is what I have tried so far. The textBoxFolderpath is being used to hold the values.

What am I missing or doing incorrectly?

Upvotes: 0

Views: 659

Answers (2)

jrdnoland
jrdnoland

Reputation: 115

Thanks Zer0 - below is what I ended up using.

private void btnCurrentFolder_Click(object sender, EventArgs e)
        {
            OpenFileDialog openDialog1 = new OpenFileDialog(); 

            // Determine starting directory
            if (chkSetToRoot.Checked)
            {
                openDialog1.InitialDirectory = @"K:\RESULTS";
            }      

            openDialog1.Title = "Select A Test File";
            openDialog1.Filter = "All Files (*.*)|*.*";

            if (openDialog1.ShowDialog() == DialogResult.OK)
            {      
                textBoxFolderpath.Text = Path.GetDirectoryName(openDialog1.FileName);
                textBoxFileName.Text = Path.GetFileName(openDialog1.FileName);
            }
        }

Upvotes: 0

Zer0
Zer0

Reputation: 7354

When working with filenames and paths I'd highly recommend using built-in classes to handle this, like the Path class:

Path.GetDirectoryName(openFileDialog1.FileName)

This returns the path, without the filename. It's also cross-platform compatible.

Upvotes: 3

Related Questions