Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get file path in textbox using windows form application?

Tags:

c#

c#-4.0

I have one browse button and one text box. In the browse_button click event, I would like to browse the files and place the path name into textbox. For this I've written code like this by using openfile dialog.

private void brwsbtn_Click(object sender, EventArgs e)
        {
            if (openFD.ShowDialog() == DialogResult.OK)
            {
                  textBox1.Text = openFD.FileName;
            }
            textBox1.Text="";
        }

So that I am able to select files only. How can I select and place the folders path in textbox?.

In my application the user should able to select either file or folder through a single browse button. Please suggest me how to write code for this.

Note. Please let me know can we use to upload file without using Openfiledialog in windows form..

like image 917
love mam Avatar asked Nov 24 '25 21:11

love mam


2 Answers

Your code don't add file path to the text box because you have this line:

textBox1.Text = "";

Which auto clear the line:

textBox1.Text = openFD.FileName;

Remove it and you can add file path to textbox:

private void brwsbtn_Click(object sender, EventArgs e)
{
    if (openFD.ShowDialog() == DialogResult.OK)
    {
        textBox1.Text = openFD.FileName;
    }
}

If you want file name only (not include path), you can use:

private void brwsbtn_Click(object sender, EventArgs e)
{
    if (openFD.ShowDialog() == DialogResult.OK)
    {
        textBox1.Text = Path.GetFileName(openFD.FileName);
    }
}
like image 178
Thanh Nguyen Avatar answered Nov 26 '25 11:11

Thanh Nguyen


Add a FolderBrowserDialog to your form. Then something like this will work:

if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
   {
      textBox1.Text = folderBrowserDialog1.SelectedPath
   }

You can also use your existing fileDialog to do

Path.GetDirectoryName(openFD.FileName);
like image 38
Samer Tufail Avatar answered Nov 26 '25 10:11

Samer Tufail



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!