另一个进程正在使用System.IO.IOException

时间:2015-01-27 04:52:18

标签: c# io ioexception

我正在尝试写入一个文件,我相信我正在关闭我之前在代码中读过的文件,但是我得到了一个" System.IO.IO.Exception"这是我读取和写入文件的代码。

public class InOutTxt
{
    public List<Employee> ReadFile(string fileName) {
        FileStream fs = new FileStream(fileName,FileMode.Open ,FileAccess.ReadWrite);
        StreamReader fileIn = new StreamReader(fileName);
        fileIn = File.OpenText(fileName);
        List<Employee> list = new List<Employee>();
        string[] test;
        string name;
        string ID;
        string dep;
        string post;

        while (!fileIn.EndOfStream || !File.Exists(fileName)) {

            string inString = fileIn.ReadLine();
            test = inString.Split('#');
            name = test[0];
            ID = test[1];
            dep = test[2];
            post = test[3];
            Employee newEmp = new Employee(name, ID, dep, post);
            list.Add(newEmp);

        }
        fileIn.Close();
        fs.Close();
        return list;
    }

    public void WriteFile(List<Employee> outList, string file) {

        FileStream fs = new FileStream(file, FileMode.Open, FileAccess.ReadWrite);
        StreamWriter writeOut = new StreamWriter(file);

        for (int i = 0; i < outList.Count; i++) {

            writeOut.WriteLine(outList[i].name + '#' + outList[i].IDnum + '#' + outList[i].department + '#' + outList[i].position);

        }
        writeOut.Close();
        fs.Close();
    }

}

错误发生在代码的这一部分

StreamReader fileIn = new StreamReader(fileName);

如果它对今天早些时候运行良好有帮助,我所做的唯一重大改变就是添加了上面的FileStream属性。

1 个答案:

答案 0 :(得分:1)

  

另一个进程使用的System.IO.IOException

您使用FileStream构造函数打开了文件,StreamReader在尝试使用fileName构造函数再次打开文件时出错。传递FileStream对象而不是fileName

FileStream Constructor (String, FileMode)

  

构造函数具有对文件的读/写访问权限   打开共享读取访问权限(即打开文件的请求)   通过这个或另一个进程写入将失败,直到FileStream   对象已关闭,但读取尝试将成功),MSDN

//File is opened by FileStream and not available for opening before it is closed.
FileStream fs = new FileStream(fileName,FileMode.Open ,FileAccess.ReadWrite); 
StreamReader fileIn = new StreamReader(fs); //Here pass fs instead of fileName