[英]System.IO.IOException: 'Process can not access the file'
我是C#编程语言的新手。 我一直在尝试开发出租传感器应用程序。 导出输出文件时,我遇到了(System.IO.IOException:另一个进程使用的文件)Exception的麻烦。 我真的找不到问题。 我想在桌面上创建当前日期和时间的文本文件。 这是我的代码:
string dateAndTime = DateTime.Now.ToShortDateString() + "-" + DateTime.Now.ToShortTimeString();
dateAndTime = dateAndTime.Replace('/', '-');
dateAndTime = dateAndTime.Replace(':', '-');
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + dateAndTime + ".txt");
if (!File.Exists(path))
{
var myFile = File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine(txtDateTym.Text + " , " + txtKQ.Text);//Creating file on given path if file was not created
myFile.Close();
}
else if (File.Exists(path))
{
using (var tw = new StreamWriter(path, true))
{
tw.WriteLine(txtDateTym.Text + " , " + txtKQ.Text);//writing real time data to text file
tw.Close();
}
}
首先,您应该更改创建路径的方式:
string path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), dateAndTime + ".txt");
您会看到dateTime
之前有一个逗号而不是加号。
其次,您应该使用从CreateFile
返回的Stream作为StreamWriter构造函数的输入参数:
TextWriter tw = new StreamWriter(myFile);
或仅保留File.Create
并在执行操作时将myPath
用作StreamWriter的输入。 StreamWriter将自己创建文件。
如果您两次使用myFile
创建文件( CreateFile
和StreamWriter
,则第二个调用将被阻止。
if (!File.Exists(path))
{
File.Create(path).Dispose();
using (TextWriter tw = new StreamWriter(path))
{
tw.WriteLine(txtDateTym.Text + " , " + txtKQ.Text);
}
}
h File.Create(path)
返回一个FileStream
,它是您尝试创建StreamWriter
时文件的句柄,该句柄已被使用
您也可以在这里查看更多信息
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.