C#空路径名称不合法

时间:2011-09-05 08:43:27

标签: c#

我是这种语言的完全初学者,目前我正在尝试创建一个简单的文本编辑应用程序,但在尝试打开文件时遇到上述错误。 下面的代码,任何帮助将不胜感激。

private void mnuOpen_Click(object sender, EventArgs e)
    {
        string chosenFile = "";

        openFD.Title = "Select a text file";
        openFD.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
        openFD.FileName = "Choose a file..";
        openFD.Filter = "Text Files|*.txt|All Files|*.*";

        if (openFD.ShowDialog() != DialogResult.Cancel)
        {
            contentBox.LoadFile(chosenFile, RichTextBoxStreamType.PlainText);
        }
    }

异常本身发生在这里:

contentBox.LoadFile(chosenFile, RichTextBoxStreamType.PlainText);

1 个答案:

答案 0 :(得分:4)

您需要将chosenFile设置为OpenFileDialog控件中所选文件的名称:

private void mnuOpen_Click(object sender, EventArgs e)
{
    string chosenFile = "";

    openFD.Title = "Select a text file";
    openFD.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.Personal);
    openFD.FileName = "Choose a file..";
    openFD.Filter = "Text Files|*.txt|All Files|*.*";

    if (openFD.ShowDialog() != DialogResult.Cancel)
    {
        // Assign the selected filename to chosenFile
        chosenFile = openFD.FileName;
        contentBox.LoadFile(chosenFile, RichTextBoxStreamType.PlainText);
    }
}