选择文件 C# 并获取目录 [英] Choose file C# and get directory

查看:22
本文介绍了选择文件 C# 并获取目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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)?

谢谢

推荐答案

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

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

这篇关于选择文件 C# 并获取目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆