Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Choose file C# and get directory

Tags:

c#

windows

I'm trying to open a file dialog box so the user can choose the location of an access database. Can someone explain how to add a file dialog when a button is clicked and also how to transform the user choice into a string that contains the file directory ( c:\abc\dfg\1234.txt)?

Thanks

like image 355
manfredini Avatar asked Dec 01 '22 17:12

manfredini


2 Answers

As you did not state the technology you use (WPF or WinForms), I assume you use WinForms. In that case, use an OpenFileDialog in your code. After the dialog was closed, you can get the selected full file name using the FileName property.

There is the following example of how to use it on the documentation page I linked above, which I modified slightly as you want the file name, not the stream:

private void button1_Click(object sender, System.EventArgs e)
{
    OpenFileDialog openFileDialog1 = new OpenFileDialog();

    openFileDialog1.InitialDirectory = "c:\\" ;
    openFileDialog1.Filter = "Database files (*.mdb, *.accdb)|*.mdb;*.accdb" ;
    openFileDialog1.FilterIndex = 0;
    openFileDialog1.RestoreDirectory = true ;

    if(openFileDialog1.ShowDialog() == DialogResult.OK)
    {
        string selectedFileName = openFileDialog1.FileName;
        //...
    }
}
like image 197
Thorsten Dittmar Avatar answered Dec 03 '22 06:12

Thorsten Dittmar


Based on your previous question I assume you are using WinForms. You can use the OpenFileDialog Class for this purpose. See the code below which will run on your button Click event assuming your button id is button1:

private void button1_Click(object sender, System.EventArgs e)
{
    OpenFileDialog openFileDialog1 = new OpenFileDialog();

    openFileDialog1.InitialDirectory = "c:\\";
    openFileDialog1.Filter = "Access files (*.accdb)|*.accdb|Old Access files (*.mdb)|*.mdb";
    openFileDialog1.FilterIndex = 2;
    openFileDialog1.RestoreDirectory = true;

    if(openFileDialog1.ShowDialog() == DialogResult.OK)
    {
       var path = openFileDialog1.FileName;
    }
}

More information.

like image 21
Umair Avatar answered Dec 03 '22 07:12

Umair