Reputation: 109
I am trying to write to a file, I believe i am closing the file that i had read in earlier in the code, but I am getting a "System.IO.IO.Exception" This is my code for reading and writing to the file.
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();
}
}
The Error is occuring at this part of the code
StreamReader fileIn = new StreamReader(fileName);
If it helps any it was running well earlier today, the only major change I have made was the addition of the FileStream attribute above.
Upvotes: 1
Views: 2305
Reputation: 148180
System.IO.IOException being used by another process
You have opened file using the FileStream
constructor and the StreamReader
gives error when it tries to open the file again using the fileName constructor. Pass the FileStream
object instead of fileName
.
FileStream Constructor (String, FileMode)
The constructor is given read/write access to the file, and it is opened sharing Read access (that is, requests to open the file for writing by this or another process will fail until the FileStream object has been closed, but read attempts will succeed), 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
Upvotes: 1