【问题标题】:Error “An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll”错误“在 mscorlib.dll 中发生类型为 'System.IO.IOException' 的未处理异常”
【发布时间】:2016-02-11 17:41:52
【问题描述】:

我收到错误

在 mscorlib.dll 中发生了“System.IO.IOException”类型的未处理异常

附加信息:进程无法访问文件>'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);
        }

这个函数试图创建一个文件并写入它。如果我禁用写入并仅保留文件创建,则功能有效。 我是编码新手,所以如果代码或我的解释中有什么愚蠢的地方,请见谅。

【问题讨论】:

    标签: c#


    【解决方案1】:

    文件在创建时被锁定,因为使用 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);
                }
            }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-18
      • 2015-12-30
      • 2016-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多