尝试从SharePoint服务器打开文件时出现C#错误(FileInfo / FileStream)

时间:2018-01-18 21:01:37

标签: c# sharepoint

我在SharePoint中有一项功能,可以将webpart添加到创建的每个新站点的webpart库中。违规行代码如下:

string webPartPath = System.Web.Hosting.HostingEnvironment.MapPath("~/" + 
CompanyConstants.CustomWebPart);
FileInfo f = new FileInfo(webPartPath);          
FileStream s = f.Open(FileMode.Open, FileAccess.Read);

字符串webPartPath的计算结果为:

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\template\layouts\*CENSORED*\*CENSORED*\WebPart\CustomWebpart.dwp

我收到的错误如下:

  

进程无法访问文件' C:\ Program Files \ Common Files \ Microsoft Shared \ Web Server Extensions \ 15 \ template \ layouts * CENSORED ** CENSORED * \ WebPart \ CustomWebpart.dwp'因为它正被另一个进程使用。

有谁知道为什么会这样?非常感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

我可以用这种方式复制问题:

  String webPartPath = @"c:\test\temp.html";
  FileInfo f = new FileInfo(webPartPath);
  FileStream s = f.Open(FileMode.Open, FileAccess.Read);

  FileInfo f2 = new FileInfo(webPartPath);
  FileStream s2 = f.Open(FileMode.Open, FileAccess.Read);

这让我相信你没有清理你正在创建的流。

将代码改为此代码(如下)。所有代码都应该在USING中。这将确保流关闭(即使出现错误)。继承IDisposable的任何对象都可以这种方式调用。

using (FileStream s = f.Open(FileMode.Open, FileAccess.Read))
{
    // Put your file reading code in here.
}

我还建议在更改代码后重新启动IIS,因为即使在进行更改后,您可能会锁定先前执行的锁定。