Click to See Complete Forum and Search --> : IOException: "cannot access the file because it is being used by another process"


tamaro
July 25th, 2007, 07:38 AM
From within my program, when the user clicks the Run button, I call a console application like this:

Process p = new System.Diagnostics.Process();
ProcessStartInfo psI = new ProcessStartInfo("cmd");
p.Start();
sw = p.StandardInput;
sw.WriteLine(strStartCommand);

The console application deletes the old output file and creates a new one every time it runs.

Depending on user input, sometimes it's run directly through the code above and sometimes through a delegate function that calls the above code.
Whenever the direct path is used after the program has already been run once before, i get an exception of type 'System.IO.IOException' (The process cannot access the file "D:\...." because it is being used by another process) when trying to delete the old output file using:

File.Delete(strOutputFile);


What's the difference between the two ways of running the code and why do I get that exception??

Thanks.

crackersixx
July 25th, 2007, 02:16 PM
You didn't include all the related code, but it's probably safe to assume you are not closing the file properly after you are done writing to it...

After all your WriteLine calls are finished, be sure to:

sw.Flush();
sw.Close();

tamaro
July 29th, 2007, 06:57 AM
as i said - it's not "me" writing the file, but the commercial application that i'm running.
if it weren't closing the file properly then the error should have occured every time it tried to access the file for the second time, but it doesn't. it occurs only when the application is called in a certain way.
it's not that simple.