我试图在没有创建Data.txt的情况下运行我的程序,但是每次执行时都会显示错误:“该进程无法访问文件'path',因为它正在被另一个进程使用。” < / p>
这里是代码有错误的区域,需要明确的是,它在显示“ StreamWriter Data = new StreamWriter(“ Data.txt”)”的行上
dataCheck = @"Data.txt";
dataExists = File.Exists(dataCheck);
if (dataExists)
{
StreamReader Data = new StreamReader(@"Data.txt");
for (i = 0; i < 5; i++)
{
//takes lines from text file and stores them in an array
activities[i] = Data.ReadLine();
}
for (i = 0; i < 5; i++)
{
try { activityTimes[i] = Int32.Parse(Data.ReadLine()); }
catch {
StreamWriter DataWrite = new StreamWriter("Data.txt");
DataWrite.Write(activities[0] + "\r\n");
DataWrite.Write(activities[1] + "\r\n");
DataWrite.Write(activities[2] + "\r\n");
DataWrite.Write(activities[3] + "\r\n");
DataWrite.Write(activities[4] + "\r\n");
DataWrite.Write(activityTimes[0] + "\r\n");
DataWrite.Write(activityTimes[1] + "\r\n");
DataWrite.Write(activityTimes[2] + "\r\n");
DataWrite.Write(activityTimes[3] + "\r\n");
DataWrite.Write(activityTimes[4] + "\r\n");
DataWrite.Close();
}
}
}
else
{
//creates data file with activities and times
File.Create(dataCheck);
StreamWriter DataWrite = new StreamWriter("Data.txt");
DataWrite.Write(activities[0] + "\r\n");
DataWrite.Write(activities[1] + "\r\n");
DataWrite.Write(activities[2] + "\r\n");
DataWrite.Write(activities[3] + "\r\n");
DataWrite.Write(activities[4] + "\r\n");
DataWrite.Write(activityTimes[0] + "\r\n");
DataWrite.Write(activityTimes[1] + "\r\n");
DataWrite.Write(activityTimes[2] + "\r\n");
DataWrite.Write(activityTimes[3] + "\r\n");
DataWrite.Write(activityTimes[4] + "\r\n");
DataWrite.Close();
}
如果有人可以解释错误/为我提供解决方案,我将不胜感激!
答案 0 :(得分:0)
在文件不存在的情况下,您遇到的问题是调用File.Create
,它将创建文件并在文件上打开流。这使您无法再在同一文件上使用StreamWriter
。删除File.Create
,因为它不是必需的:StreamWriter
将创建文件。
其他一些技巧:StreamReader
和StreamWriter
都是IDisposable
,因此都应放在using
块中。另外,这避免了您需要调用Close
的情况,该调用由隐式Dispose
完成。您应该将这些using
块视为打开文件的时间段,因此,由于它们正在访问文件,因此它们不必重叠。
考虑使用DataWrite.Write(activities[0] + "\r\n");
而不是DataWrite.WriteLine(activities[0]);
。
您已经声明了一个变量来保存文件名,因此请使用该变量,而不要在多个位置复制文件名。
有两个相同的大块代码创建文件。将其重构为方法,然后从两个地方调用该方法。
答案 1 :(得分:0)
您正在尝试通过指定文件名来创建指向同一文件的StreamReader
和StreamWriter
(并在打开第二个文件之前不关闭第一个文件)。你不能那样做。例如,此代码将产生相同的结果:
public static void Main()
{
StreamWriter sw = new StreamWriter("data.txt");
StreamReader sr = new StreamReader("data.txt"); //: 'The process cannot access the
// file 'data.txt' because it is being used
// by another process.'
}
相反,您可以创建一个FileStream
,然后从该StreamWriter
中创建一个StreamReader
和FileStream
。见下文:
public static void Main()
{
using (var fs = new FileStream("data.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (var sw = new StreamWriter(fs, Encoding.ASCII, 1024, true))
using (var sr = new StreamReader(fs, Encoding.ASCII, false, 1024, true))
{
sw.WriteLine("Hi");
sw.Flush(); //Make sure everything is fully written to the file.
fs.Position = 0; //Go back to the beginning of the file, so we can read it.
Console.WriteLine(sr.ReadLine()); //Hi
}
}
}