C#StreamReader即使我关闭也会阻止该过程

时间:2015-10-13 01:57:06

标签: c# file-io streamreader

我目前收到这些错误:

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相当新,对我来说看起来好像一切都正确?关于我为什么会收到这些错误的任何建议?

3 个答案:

答案 0 :(得分:0)

我已经面对这个问题了很多次,它说"进程无法访问文件&bin; \ Debug \ Some.exe'因为它正在被另一个进程使用。"

通常你应该清理解决方案并重新构建,这样可以解决问题。

Build -> Clean Solution

然后

Build -> Rebuild Solution

如果这不能解决问题。比你应该从bin文件夹手动删除Soldier.exe并再次构建解决方案

答案 1 :(得分:0)

首先,我建议使用。这样,即使您最终获得异常,文件也将被关闭(并且阅读器已被处理)。 另一方面,如果ReadLine到达流的末尾,则返回null。 但StreamReader中有一个有用的属性:EndOfStream。当你到达流的末尾时,这是真的。

所以我建议这样的代码:

public Form1()
{
    if(File.Exists("soldier.csv"))
    {
        InitializeComponent();
        using (StreamReader sr = new StreamReader("soldier.csv"))
        {
            string stream_line;
            int intCommaIndex1 = 0;
            int intCommaIndex2;
            string strSubStringSect;
            while (!sr.EndOfStream)
            {
                stream_line = sr.ReadLine();
                intCommaIndex1 = stream_line.IndexOf(",", intCommaIndex1);
                intCommaIndex2 = stream_line.IndexOf(",", intCommaIndex1);
                strSubStringSect = stream_line.Substring(intCommaIndex1, intCommaIndex2);
                richTextBox1.Text = richTextBox1.Text + " " + strSubStringSect;
                intCommaIndex1 = intCommaIndex2;
            }
        }
    }

}

答案 2 :(得分:0)

由于“托管过程”,在Visual Studio上进行调试时会发生这种情况。你的正在运行的进程是否有vshost.exe?

关闭Visual Studio,重新打开解决方案,然后尝试以下操作:

  1. 在“项目”菜单上,单击“属性”。
  2. 单击“调试”选项卡。
  3. 清除“启用Visual Studio宿主进程”复选框。
  4. 如果vshost.exe仍然保留您的文件,这可能会解决您的问题。