0

I'm trying to write to a file called output.txt. It's fine the first time my code runs but the second time it throws an exception:

The process cannot access output1.txt because it is being used by another process

But I'm using this in a using statement, and it should be disposed of and the file should be unlocked.

The constructor says if the file exists, it can either be appended to or overwritten. Doesn't seem to be doing this because of the IOException it is throwing.

Why is this happening?

using (System.IO.StreamWriter file = new System.IO.StreamWriter(@directoryURL + "\\output"+outputNumber+".txt", true))
{
    foreach (string line in splitOutput)
    {
        file.WriteLine(line);
    }
}
Thomas Weller
  • 55,411
  • 20
  • 125
  • 222
user3519261
  • 79
  • 1
  • 14
  • Be sure that you application process is not still running in the background. If the process is still running kill it. If that doesn't work, try restarting. – James Parsons Oct 07 '15 at 21:29
  • The file is not open anywhere. – user3519261 Oct 07 '15 at 21:36
  • I mean the program that is reading it. Sometimes, when closed incorrectly, the process may stay behind. – James Parsons Oct 07 '15 at 21:36
  • related: [Does disposing a StreamWriter close the underlying Stream?](http://stackoverflow.com/questions/1187700/does-disposing-a-streamwriter-close-the-underlying-stream) – Thomas Weller Oct 07 '15 at 21:42
  • The stream should close after the using statement anyway. I've tried to add a `file.Dispose()` in there but problem still persists. – user3519261 Oct 07 '15 at 21:51

1 Answers1

1

There are many reasons why a file can still be locked, e.g. virus scanners.

Use SysInternals Process Explorer, "Find Handle" (Ctrl+F), enter your file name and see which application has your file in use.

You have identified urltest.vshost.exe as the culprit (mentioned in a comment), so it must be your code...

In the code provided via PasteBin, I see the following loop

foreach (string file in fileEntries)
{
    StreamReader fileStream = new StreamReader(file);
    ...
    FileHander(fileStream, extension, websiteURL, fileName);
}

This opens many file streams, but FileHandler() only operates on certain extensions:

private void FileHander(StreamReader fileStream, string extension, string websiteURL, string fileName)
{
    switch (extension)
    {
        ...
        CheckPowershell(fileStream, websiteURL, fileName);
        ...
    }
} 

And only CheckPowershell() closes the files:

private void CheckPowershell(StreamReader fileStream, string websiteURL, string fileName)
{
    ...
    fileStream.Close();
}

So all files which do not have a specific extension (such as .txt) remain open.

A quick solution seems to move the Close() from CheckPowershell() to FileHander(). A more professional way would need more refactoring.

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222