Morgan T.
Morgan T.

Reputation: 1937

C# write an uploaded file to a UNC with FileStream, read it later sometimes doesn't work

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

Upvotes: 0

Views: 1768

Answers (1)

helb
helb

Reputation: 7793

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
}

Upvotes: 1

Related Questions