如何创建文本框以保存路径

时间:2013-01-29 17:06:32

标签: c# visual-studio-2010 windows-forms-designer

我已经看过很多次,有textbox之类的程序用于获取/保存某些内容的path ......上面有一个按钮,当你点击它时它会打开一个提示您选择目录,你知道吗? 我怎么能这样做? 我必须阅读file.txt,我需要我的应用程序打开此file.txt,我如何打开此“提示符”?然后我需要以同样的方式保存destination path ......它实际上是textbox还是其他什么?

由于

3 个答案:

答案 0 :(得分:2)

您需要在文本框旁边创建一个按钮。

在按钮的Click事件处理程序中,创建并显示SaveFileDialog,然后将其结果分配给文本框的文本。

答案 1 :(得分:2)

您需要在表单(MSDN has more info

中添加OpenFileDialog

这个样本应该比我更好地解释它!

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

openFileDialog1.InitialDirectory = "c:\\" ;
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
openFileDialog1.FilterIndex = 2 ;
openFileDialog1.RestoreDirectory = true ;

if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
    try
    {
        if ((myStream = openFileDialog1.OpenFile()) != null)
        {
            using (myStream)
            {
                // Insert code to read the stream here.
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
    }
}
}

答案 2 :(得分:1)

您可以使用OpenFileDialog

string path;
OpenFileDialog file = new OpenFileDialog();
if (file.ShowDialog() == DialogResult.OK)
{
    path = file.FileName;
}

现在文件路径保存到字符串中,然后您可以操作该文件。