0

I have he following code

    HttpPostedFileBase files = Request.Files[0];
    Stream fileStream = files.InputStream;

    using (Stream file = System.IO.File.OpenWrite(originalImage))
    {
        StreamUtil.CopyStream(fileStream, file);
        file.Close();
        fileStream.close();
        fileStream.dispose();
    }

    // here is CopyStream method

    public static void CopyStream(Stream input, Stream output)
    {
        var buffer = new byte[8*1024];
        int len;
        while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            output.Write(buffer, 0, len);
        }
    }

When i try to write the same file twice i get

The process cannot access the file \u0027D:FILENAME because it is being used by another process

How can i close this ?so once the request the writing is done, it will be closed?

DarthVader
  • 52,984
  • 76
  • 209
  • 300

1 Answers1

0

I wanted to write it as a comment but it is not clear so:

Try doing something like this:

MemoryStream fileStream = new MemoryStream();

fileStream.WriteByte(04);

using (Stream file = System.IO.File.OpenWrite(originalImage))
{
    CopyStream(fileStream, file);
}

using (Stream file = System.IO.File.OpenWrite(originalImage))
{
    CopyStream(fileStream, file);
}

Do you get the same error on the second using line?

Writwick
  • 2,133
  • 6
  • 23
  • 54
eyossi
  • 4,230
  • 22
  • 20
  • I am trying to check if you get the same message if you open the file right after you close it (because i think the file is not locked from your posted code, but from somewhere else). If you will try to open it twice and you won't get the message you can be sure that the file is locked from somewhere else. – eyossi May 20 '12 at 13:35
  • that s really not a valid solution what i did was to add date time ticks to file name so it wont be same file again – DarthVader May 20 '12 at 23:06
  • I said i wanted to write it as a comment and not as an answer... but from your answer i guess i know what happend! i think you had the same code running from multiple threads **using the same file name** and then if two threads were running on the same time then the first one would succeed opening the file and the second will get the error message. am i right? – eyossi May 21 '12 at 06:00
  • That means that you get exception on the second Stream file = System.IO.File.OpenWrite(originalImage) call??? – eyossi May 21 '12 at 14:30
  • i didnt try. my workaround was prepend datetime to the beginning of the file, so it creates a new file everytime, user uploads. – DarthVader May 21 '12 at 17:05