【问题标题】:Unable to create a text file in windows form, getting error 'System.ArgumentException'无法以 Windows 形式创建文本文件,出现错误“System.ArgumentException”
【发布时间】:2016-03-23 18:46:49
【问题描述】:

我制作了一个按钮,所以当我点击它时,它会打开一个目录,我可以从中创建一个文本文件,我点击按钮,它会很好地打开目录,我可以为文本文件命名我想要的单击保存,但随后我收到一条错误消息,提示“mscorlib.dll 中发生了 'System.ArgumentException' 类型的未处理异常”

这是我的代码:

    private void createAlgorithmsAndComplexityNotesToolStripMenuItem_Click(object sender, EventArgs e)
    {
        SaveFileDialog sfd = new SaveFileDialog();
        sfd.Filter = "Text File|*.txt";
        sfd.FileName = "Algorithms And Complexity Lecture Notes";
        sfd.Title = "Algorithms And Complexity Lecture Notes";
        if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            string path = sfd.FileName;
            StreamWriter write = new StreamWriter(File.Create("C:\\Users\antho\\Desktop\\Folder\\Uni\\Programming and data structures\\Assignment 2\\Modules"));
            write.Write(writeFile);
            write.Close();
        }
    }

【问题讨论】:

  • 使用调试器..它抛出错误的哪一行..?是这条线吗StreamWriter write = new StreamWriter(File.Create("C:\\Users\antho\\Desktop\\Folder\\Uni\\Programming and data structures\\Assignment 2\\Modules"));
  • @MethodMan 是的,就是那一行,它还说路径中有非法字符。
  • 那是因为你的文件路径中有空格可能你为什么不尝试写入像"@c:\Users\antho\" 这样的文件路径查看这篇文章以更轻松地创建文件名stackoverflow.com/questions/27823789/…
  • 你还需要在你的超长文件路径中有一个尾随"\\"..再一次你甚至从来没有创建一个文件,因为你从来没有告诉File.CreateFilePath + FileName.txt是什么......
  • 首先,你不使用文件名,savedialog 给你,但你总是写入一个名为Modules 的文件。也许已经有一个具有该名称的文件夹。其次,您忘记转义文件名中的第二个反斜杠(antho 之前的那个)。我不确定\a 是否是有效字符。但它绝对不是文件路径中的有效字符,

标签: c# button text-files windows-forms-designer writefile


【解决方案1】:

首先将你的路径放在一个变量中,然后检查目录是否存在(如果不存在,则创建它)。

(注意单反斜杠)

string path = @"C:\Users\antho\Desktop\Folder\Uni\Programming and data structures\Assignment 2\Modules";
string fileName = sfd.FileName;

if (!Directory.Exists(path))
{
    Directory.CreateDirectory(path);
}

其次,使用 Path.Combine() 构造路径。您在 File.Create 中设置的路径必须以文件名结尾。

我还建议使用 File.WriteAllText() 来创建简单的文件(就像在您的代码中一样)。这样您就不必费心关闭它了。

File.WriteAllText(Path.Combine(path, fileName), writeFile);

【讨论】:

    【解决方案2】:

    您的问题在于您提供的文件路径。

    "C:\\Users\antho\\Desktop\\Folder\\Uni\\Programming and data structures\\Assignment 2\\Modules"
    

    您忘记在此处转义反斜杠:Users\antho。

    在这种情况下,\a 被解释为单个字符,这在文件名中是非法的。甚至不确定这是否是现有角色。

    【讨论】:

      猜你喜欢
      • 2012-12-24
      • 2015-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-09-12
      • 2014-02-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多