如何使用FileOpenDialog

时间:2016-05-17 11:57:11

标签: c# .net visual-studio

我试图通过按下按钮来打开文件(标签更精确,但它的工作方式相同)

出于某种原因,当FileDialog打开并且我选择文件并按下打开它没有打开文件它只关闭FileDialog

private void selectLbl_Click(object sender, EventArgs e)
{

    OpenFileDialog ofd = new OpenFileDialog();
    ofd.InitialDirectory = "c:\\";
    ofd.Filter = "Script files (*.au3)|*.au3";
    ofd.RestoreDirectory = true;
    ofd.Title = ("Select Your Helping Script");


    if (ofd.ShowDialog() == DialogResult.OK)
    {
        ofd.OpenFile(); //Not sure if there is supposed to be more here
    }
}

3 个答案:

答案 0 :(得分:3)

ofd.OpenFile();

将文件内容作为字节流返回,如here所述。如果要按照描述的方式打开文件,请使用

if (ofd.ShowDialog() == DialogResult.OK)
{
  System.Diagnostics.Process.Start(ofd.FileName);
}

因此,您选择的文件将以关联的应用程序开头。

答案 1 :(得分:1)

ofd.OpenFile()将用户选择的文件打开为Stream,您可以使用该文件从文件中读取。

您对该流的处理取决于您要实现的目标。例如,您可以读取并输出所有行:

if (ofd.ShowDialog() == DialogResult.OK)
{
    using (TextReader reader = new StreamReader(ofd.OpenFile()))
    {
        string line;
        while((line = t.ReadLine()) != null)
            Console.WriteLine(line);
    }
}

或者如果是xml文件,您可以将其解析为xml:

if (ofd.ShowDialog() == DialogResult.OK)
{
    using(XmlTextReader t = new XmlTextReader(ofd.OpenFile()))
    {
        while (t.Read())
            Console.WriteLine($"{t.Name}: {t.Value}");
    }
}

答案 2 :(得分:0)

OpenFileDialog不是打开文件的对话框。它只与操作员通信,如果程序需要知道要打开哪个文件,则通常会显示该对话框。所以它只是一个对话框,而不是文件开启者。

如果用户按下确定或取消,您决定该怎么做:

private void selectLbl_click(object sender, ...)
{
    using (OpenFileDialog ofd = new OpenFileDialog())
    {
        ofd.InitialDirectory = "c:\\";
        ofd.Filter = "Script files (*.au3)|*.au3";
        ofd.RestoreDirectory = true;
        ofd.Title = ("Select Your Helping Script");

        var dlgResult = ofd.ShowDialog(this);
        if (dlgResult == DialogResult.OK)
        {    // operator pressed OK, get the filename:
             string fullFileName = ofd.FileName;
             ProcessFile(fullFileName);
        }
    }
}


if (ofd.ShowDialog() == DialogResult.OK)
{
    ofd.OpenFile(); //Not sure if there is supposed to be more here
}