0

I am tired of these exceptions being thrown on production server where I am getting bunch of files from document library and downloading them to a folder directory on server.

Worse thing is that it happens once in 10 maybe or once in 20, it's quiet random there isn't no pattern at all.

I am using this code if I can improve it somehow,

SPSecurity.RunWithElevatedPrivileges(delegate()
                    {
                        using (SPSite spSite = new SPSite(siteUrl))
                        using (SPWeb spWeb = spSite.OpenWeb())
                        {
                            SPDocumentLibrary library = spWeb.Lists[listName] as SPDocumentLibrary;

                            foreach (SPListItem listItem in library.Items)
                            {
                                SPFile file = listItem.File;
                                byte[] document = file.OpenBinary();
                                System.IO.Directory.CreateDirectory(Path);
                                System.IO.FileStream stream = System.IO.File.Create(Path + file.Name);
                                stream.Write(document, 0, document.Length);
                                stream.Close();
                            }
                        }
                    });   

Error

Couldn't access file even though if I try it again in a moment it works fine.

Mathematics
  • 7,314
  • 25
  • 77
  • 152

2 Answers2

0

I would try to encapsulate the open/close logic using the using statement

using(FileStream stream = System.IO.File.Create(Path + file.Name))
{
    stream.Write(document, 0, document.Length);
}

This will close the stream, but also dispose it.

Steve
  • 213,761
  • 22
  • 232
  • 286
0

Have you tried to turn it thread-safe with a lock like this?:

lock(Path + file.Name) {
    System.IO.Directory.CreateDirectory(Path);
    System.IO.FileStream stream = System.IO.File.Create(Path + file.Name);
    stream.Write(document, 0, document.Length);
    stream.Close();
}

And also open files as shared and ensure the write stream is closed in the catch clause.

kpull1
  • 1,623
  • 15
  • 19