Click to See Complete Forum and Search --> : .NET StreamWriter Error


draghuna
August 29th, 2006, 03:46 PM
I have the following code to in my application but when I try to run the application I am getting the error

"The process cannot access the file "BATCHFIle.bat" because it is being used by another process"

//Function 1

public void Function1()
{
StreamReader strmReader = new StreamReader(tempBatchFileName);
StreamWriter strmWriter = new StreamWriter(BatchFileName);
while(strmReader.Peek() != -1)
{
string currentLine = strmReader.ReadLine();
strmWriter.WriteLine(currentLine);
}
strmReader.Close();
strmWriter.Close();
}


//Function2

public string Function2()
{

System.IO.StreamReader strm = System.IO.File.OpenText(BatchFileName);

while(strm.Peek() != -1)
{
console.WriteLine(strm.ReadLine());
}
return "test";
}


Any idea whats causing this issue. I am closing it in the first Function but still not able to access it.

bewa
August 30th, 2006, 03:04 AM
I think you should put in Funciton1, before you close the streamwriter, strmWriter.Flush();

This might not solve your problem, but it's a good programming to put it there.

boudino
August 30th, 2006, 03:08 AM
In Function2, you doesn't close the strem. Genraly, it is recommended to use using statement to work with stream. See the example.


public void Function1()
{
using (
StreamReader strmReader = new StreamReader(tempBatchFileName);
StreamWriter strmWriter = new StreamWriter(BatchFileName);
){
while(strmReader.Peek() != -1)
{
string currentLine = strmReader.ReadLine();
strmWriter.WriteLine(currentLine);
}
}


But don't forget: the file can be opened (and holded) by totaly different process like Notepad. Also keep in mind: always Dispose() any object which is using external resources (like file). Using statement does it for you, but keep it in mind.