错误“mscorlib.dll 中发生类型为'System.IO.IOException'的未处理异常”

本文关键字:IOException IO System 未处理 异常 mscorlib 类型 错误 dll | 更新日期: 2023-09-27 18:34:10

我收到错误

mscorlib 中发生了类型为"System.IO.IOException"的未处理异常.dll

其他信息:进程无法访问文件>'c:''Tvarkarastis''Tvarkarastis.txt",因为它正被另一个进程使用。

当我尝试使用

private void sukurtiFailąToolStripMenuItem_Click(object sender, EventArgs e)
    {
        string pathString = System.IO.Path.Combine(@"c:'", "Tvarkarastis");
        System.IO.Directory.CreateDirectory(pathString);
        string fileName = "Tvarkarastis.txt";
        pathString = System.IO.Path.Combine(pathString, fileName);
        System.IO.File.Create(pathString);
        richTextBox1.Clear();
        pathString = System.IO.Path.Combine(@"c:'Tvarkarastis", "Tvarkarastis.txt");
            string[] lines = { "First line", "Second line", "Third line" };
            richTextBox1.AppendText("Prašome atsidaryti failą ir jį pakeisti. Failas yra : " + pathString + Environment.NewLine);
            System.IO.File.WriteAllLines(pathString, lines);
        }

此函数尝试创建文件并写入该文件。如果我禁用写入并只保留文件创建,函数有效。我是编码新手,所以如果代码或我的解释中有一些愚蠢的东西,请原谅我。

错误“mscorlib.dll 中发生类型为'System.IO.IOException'的未处理异常”

该文件在

创建时被锁定,因为使用 File.create() 为新文件生成 FileStream,创建文件时,您应该在 using 指令中进行创建,然后从那里继续您的代码:

        using (StreamWriter sw = new StreamWriter(File.Create(pathString)))
        {
            richTextBox1.Clear();
            string[] lines = { "First line", "Second line", "Third line" };
            richTextBox1.AppendText("Prašome atsidaryti failą ir jį pakeisti. Failas yra : " + pathString + Environment.NewLine);
            foreach (var line in lines)
            {
                sw.WriteLine(line);
            }
        }