选择文件C#并获取目录

时间:2015-07-08 13:44:24

标签: c# windows

我尝试打开文件对话框,以便用户可以选择访问数据库的位置。有人可以解释在单击按钮时如何添加文件对话框,以及如何将用户选择转换为包含文件目录的字符串(c:\ abc \ dfg \ 1234.txt)?

由于

4 个答案:

答案 0 :(得分:8)

由于您没有说明您使用的技术(WPF或WinForms),我假设您使用的是WinForms。在这种情况下,请在代码中使用OpenFileDialog。关闭对话框后,您可以使用FileName属性获取所选的完整文件名。

下面有一个关于如何在我上面链接的文档页面上使用它的示例,我根据您的需要稍微修改了文件名,而不是流:

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;
        //...
    }
}

答案 1 :(得分:1)

基于您以前的question我假设您使用的是WinForms。 您可以使用OpenFileDialog类来实现此目的。假设您的按钮ID为Click,请参阅下面的代码,该代码将在您的按钮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

答案 2 :(得分:0)

实际上相当简单

namespace YourProgram
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        string path = "";

        //Declare the File Dialog
        OpenFileDialog ofd = new OpenFileDialog();

        private void button1_click(object sender, EventArgs e)
        {
            if (odf.ShowDialog() == DialogResult.OK)
            {
                path = ofd.FileName;
            }
        }
    }
}

答案 3 :(得分:0)

假设您确实有一个带按钮的表单( button1 )......

在构造函数钩子中进入button1的click事件

...
button1.Click += button1_Click;
...

然后定义处理函数并根据需要使用System.Windows.Forms.OpenFileDialog。

void button1_Click(object sender, EventArgs e)
{
  string oSelectedFile = "";
  System.Windows.Forms.OpenFileDialog oDlg = new System.Windows.Forms.OpenFileDialog();
  if (System.Windows.Forms.DialogResult.OK == oDlg.ShowDialog())
  {
    oSelectedFile = oDlg.FileName;

    // Do whatever you want with oSelectedFile
  }
}