我收到以下运行时错误:“写入文件时出现I / O错误:”进程无法访问文件bin \ Debug / test.txt,因为它正由另一个进程使用。“
我已经关闭了所有写入文件的文件,除了使用File.ReadAllText(path)的情况,因为我的理解是文件流自动关闭。如何更正此错误?
以下是相关代码:
StreamReader sr = null;
sr = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read));
try
{
// Open the file for reading; assumes file exists
sr = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read));
while (!sr.EndOfStream)
{
line = sr.ReadLine();
fields = line.Split(',');
aniNameCol1[count] = fields[0];
aniNameCol2[count] = fields[1];
aniNameCol3[count] = fields[2];
aniNameCol4[count] = fields[3];
count++;
}
sr.Close();
sr.Dispose();
}
catch (FileNotFoundException)
{
MessageBox.Show("File Not Found" + path);
}
catch (Exception ex)
{
MessageBox.Show("Error while reading the file: " + ex.GetType().ToString() + ": " + ex.Message);
}
finally
{
if (sr != null)
{
sr.Close();
sr.Dispose();
}
}
try
{
string input = File.ReadAllText(path);
int i = 0;
int j = 0;
foreach (var row in input.Split('\n'))
{
j = 0;
foreach (var col in row.Trim().Split(','))
{
twoDArray[i, j] = col.Trim().ToString();
j++;
}
i++;
}
}
catch (FileNotFoundException)
{
MessageBox.Show("File Not Found" + path);
}
catch (Exception ex)
{
MessageBox.Show("Error while reading the file: " + ex.GetType().ToString() + ": " + ex.Message);
}
在另一种方法中,文本写在文件中:
StreamWriter sw = null;
try
{
// open the same file for writing
sw = new StreamWriter(new FileStream(path, FileMode.Create, FileAccess.Write));
for(int i = 0; i < rowMax; i++)
{
for(int j = 0; j < colMax; j++)
{
sw.WriteLine(twoDArray[i, j].ToString() + ", ");
}
}
sw.Close();
sw.Dispose();
}
catch (IOException ex)
{
MessageBox.Show("I/O error while writing the file: " + ex.Message);
}
catch (Exception ex)
{
MessageBox.Show("Unanticipated error occurred while writing: " + ex.GetType() + "; " + ex.Message);
}
finally
{
if (sw != null)
{
sw.Close();
sw.Dispose();
}
}
答案 0 :(得分:4)
你的前几行:
StreamReader sr = null;
// opened the first time
sr = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read));
try
{
// opened it a second time
sr = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read));
您的操作系统在文件上有2个共享读取访问权限 - 您只是关闭/处置其中一个。
切换到
using (var fs = new FileStream(path, FileMode.Open, FileAccess.Read))
{
using (var sr = new StreamReader(fs))
{
// do your stuff here, no need to close or flush - it is autoclosed
// when leaving the block. Do the same for writing.
}
}
它更强大,特别是如果发生异常,因为它将被关闭,无论如何。
在此帖子中详细了解using( ... )
:What are the uses of "using" in C#
编辑:堆叠使用FileStream和StreamReader
答案 1 :(得分:1)
在您的第二个代码块中,怀疑您的代码未能调用sw.Dispose()
,原因如下:
来自.NET源代码
public override void Close() {
Dispose(true);
GC.SuppressFinalize(this);
}
因此,当您致电.Close()
时,框架将调用Dispose(true)
。因此,当您明确撰写sw.Dispose()
时,您将尝试处置已经处置的StreamWriter
。
删除sw.Dispose()
答案 2 :(得分:-1)
Windows不允许两个进程共享文件系统流,因此您无法解决问题,但您可以等待文件使用,然后再访问它。
我建议你避免使用loopE来提出解决方案(for
,while
或递归调用),因为它们可能会导致内存泄漏。相反,我建议你使用旋转循环(这是一个等待下一个时钟周期到达下一次迭代的循环)。
这种循环已经在大多数语言中实现,例如C#。
首先,导入此内容:
using System.Threading;
然后,调用SpinWait.SpinUntil
传递Func<bool>
委托作为参数:该委托将被调用,直到它返回true
条件。
SpinWait.SpinUntil(delegate
{
try
{
File.Open("yourPath", FileMode.Open, FileAccess.Read, FileShare.None);
}
catch
{
return false;
}
return true;
});
此时,您还在等待,直到您可以打开该文件的流,然后打开它!
显然,你也可以创建一个有用的类:
using System.Diagnostics;
using System.Threading;
public class HardFileStream : FileStream
{
[DebuggerHidden, DebuggerStepperBoundary]
private static T Preconstructor<T>(T value, string path)
{
SpinWait.SpinUntil(delegate
{
try
{
using (File.Open(path, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
}
}
catch
{
return false;
}
return true;
});
Thread.MemoryBarrier();
return value;
}
[DebuggerHidden, DebuggerStepperBoundary]
public HardFileStream(string path, FileMode mode)
: base(Preconstructor(path, path), mode)
{
}
[DebuggerHidden, DebuggerStepperBoundary]
public HardFileStream(string path, FileMode mode, FileAccess access)
: base(Preconstructor(path, path), mode, access)
{
}
[DebuggerHidden, DebuggerStepperBoundary]
public HardFileStream(string path, FileMode mode, FileAccess access, FileShare share)
: base(Preconstructor(path, path), mode, access, share)
{
}
[DebuggerHidden, DebuggerStepperBoundary]
public HardFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize)
: base(Preconstructor(path, path), mode, access, share, bufferSize)
{
}
[DebuggerHidden, DebuggerStepperBoundary]
public HardFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, FileOptions options)
: base(Preconstructor(path, path), mode, access, share, bufferSize, options)
{
}
[DebuggerHidden, DebuggerStepperBoundary]
public HardFileStream(string path, FileMode mode, FileAccess access, FileShare share, int bufferSize, bool useAsync)
: base(Preconstructor(path, path), mode, access, share, bufferSize, useAsync)
{
}
[DebuggerHidden, DebuggerStepperBoundary]
public HardFileStream(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options)
: base(Preconstructor(path, path), mode, rights, share, bufferSize, options)
{
}
[DebuggerHidden, DebuggerStepperBoundary]
public HardFileStream(string path, FileMode mode, FileSystemRights rights, FileShare share, int bufferSize, FileOptions options, FileSecurity fileSecurity)
: base(Preconstructor(path, path), mode, rights, share, bufferSize, options, fileSecurity)
{
}
}
然后,您可以使用HardFileStream
代替FileStream
(除非您使用文件句柄,我的班级尚不支持此功能):
StreamReader sr = new StreamReader(new HardFileStream(path, FileMode.Open, FileAccess.Read));