0

我厌倦了在生产服务器上抛出这些异常,我从文档库中获取一堆文件并将它们下载到服务器上的文件夹目录。

更糟糕的是,它可能 10 次或 20 次发生一次,它是安静随机的,根本没有模式。

如果我能以某种方式改进它,我正在使用此代码,

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();
                            }
                        }
                    });   

错误

即使我稍后再试一次,它也无法访问文件。

4

2 回答 2

0

我会尝试使用using 语句封装打开/关闭逻辑

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

这将关闭流,但也会处理它。

于 2013-09-18T10:32:03.520 回答
0

你有没有试过用这样的锁把它变成线程安全的?:

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();
}

并且还以共享方式打开文件,并确保在 catch 子句中关闭写入流。

于 2013-09-18T10:32:31.610 回答