【发布时间】:2015-10-13 01:57:05
【问题描述】:
我目前收到以下错误:
Error 18 Could not copy "obj\Debug\SoldierApp.exe" to "bin\Debug\SoldierApp.exe". Exceeded retry count of 10. Failed.
Error 19 Unable to copy file "obj\Debug\SoldierApp.exe" to "bin\Debug\SoldierApp.exe". The process cannot access the file 'bin\Debug\SoldierApp.exe' because it is being used by another process.
所以我猜我的StreamReader 没有在某处适当关闭。虽然我知道我已经关闭了它。这是我的代码。
public Form1()
{
InitializeComponent();
if(File.Exists("soldier.csv"))
{
sr = new StreamReader("soldier.csv");
string stream_line;
int intCommaIndex1 = 0;
int intCommaIndex2;
string strSubStringSect;
stream_line = sr.ReadLine();
while(stream_line != EOF) //EOF is a constant
{
intCommaIndex1 = stream_line.IndexOf(",", intCommaIndex1);
intCommaIndex2 = stream_line.IndexOf(",", intCommaIndex1);
strSubStringSect = stream_line.Substring(intCommaIndex1, intCommaIndex2);
richTextBox1.Text = richTextBox1.Text + " " + strSubStringSect;
intCommaIndex1 = intCommaIndex2;
stream_line = sr.ReadLine();
}
sr.Close(); //closed here!
}
}
C# 文件 IO 相当新,对我来说似乎一切都正确?关于我为什么会收到这些错误的任何建议?
【问题讨论】:
-
那么您应该使用
using语句开始,而不是手动调用Close()。否则,如果抛出异常,您不会调用Close。此外,它看起来像是一个实例变量 - 几乎可以肯定,将其设为局部变量会更好...... -
哦,但它无法复制的文件不是您正在阅读的文件。我怀疑您仍在运行该应用程序的一个实例,这就是为什么您无法构建需要复制到同一位置的更新版本的原因。
-
我没有实例。那是我的问题。我不能使用
using,因为我们的教授没有教过,我知道这很荒谬,因为这不是我们在现实世界中最好的案例方法。这就是让我厌烦的地方。我已经阅读了 c# msdn 或其他内容,但我需要使用Close,但我会尝试关闭计算机并重新启动。我确实不小心从 whileEOF出现了一个无限循环,并且没有重新启动stream_line读取 -
如果您不能使用
using,则将所有内容包装在try-catch中,并在finally块中调用Close。 -
“我没有启动实例” - 好吧,检查任务管理器。但问题不在于 StreamReader,因为那不是同一个文件......
标签: c# file-io streamreader