![](/img/trans.png)
[英]Error “An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll”
[英]Error “An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll”
我得到错误
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);
}
该函数尝试创建文件并写入文件。 如果我禁用写入功能并且仅保留文件创建功能,则该功能有效。 我是编码的新手,如果代码或我的解释有些愚蠢,请原谅。
该文件在创建时被锁定,因为使用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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.