0

I've got a rare case where a file cannot be read from a UNC path immediately after it was written. Here's the workflow:

  1. plupload sends a large file in chunks to a WebAPI method
  2. Method writes the chunks to a UNC path (a storage server). This loops until the file is completely uploaded.
  3. After a few other operations, the same method tries to read the file again and sometimes it cannot find the file

It only seems to happen after our servers have been idle for a while. If I repeat the upload a few times, it starts to work.

I thought it might be a network configuration issue, or something to do with the file not completely closing before being read again.

Here's part of the code that writes the file (is the filestream OK in this case?)

SaveStream(stream, new FileStream(fileName, FileMode.Append, FileAccess.Write));

Here's SaveStream definition:

 private static void SaveStream(Stream stream, FileStream fileStream)
    {
        using (var fs = fileStream)
        {
            var buffer = new byte[1024];

            var l = stream.Read(buffer, 0, 1024);
            while (l > 0)
            {
                fs.Write(buffer, 0, l);
                l = stream.Read(buffer, 0, 1024);
            }
            fs.Flush();
            fs.Close();
        }
    }

Here's the code that reads the file:

var fileInfo = new FileInfo(fileName);
var exists = fileInfo.Exists;

It's the fileInfo.Exists that is returning false.

Thank you

Morgan T.
  • 1,937
  • 1
  • 17
  • 20

1 Answers1

1

These kind of errors are mostly due to files not closed yet. Try passing the fileName to SaveStream and then use it as follows:

private static void SaveStream(Stream stream, string fileName)
{
    using (var fs = new FileStream(fileName, FileMode.Append, FileAccess.Write))
    {
        var buffer = new byte[1024];

        var l = stream.Read(buffer, 0, 1024);
        while (l > 0)
        {
            fs.Write(buffer, 0, l);
            l = stream.Read(buffer, 0, 1024);
        }
        fs.Flush();
    } // end of using will close and dispose fs properly
}
helb
  • 7,609
  • 8
  • 36
  • 58
  • Yea I had a suspicion about the filestream being created in the parent method would not dispose of it properly. – Morgan T. Sep 25 '13 at 20:30
  • Ah I tried the refactor and got the same effect :( Thanks anyway – Morgan T. Sep 25 '13 at 21:03
  • Make sure the FileInfo.Exists() call is guaranteed to be executed after the SaveStream() call. If these two calls are made in separate web requests, FileInfo.Exists() may be called before the file is completely written. – helb Sep 25 '13 at 21:24