0
votes

I have a feature in SharePoint that adds a webpart to the webpart gallery of every new site that is created. The offending lines of code are as follows:

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

The string webPartPath evaluates to this:

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

The error I receive is as follows:

The process cannot access the file 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\template\layouts*CENSORED**CENSORED*\WebPart\CustomWebpart.dwp' because it is being used by another process.

Does anyone know why this may be happening? Thanks so much in advance for your help.

1

1 Answers

0
votes

I can duplicate the issue in this way:

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

It leads me to believe that you are not cleaning up the stream that you are creating.

Change your code to this instead (below). All code should be inside the USING. This will ensure the stream is closed (even if there is an error). Any objects that inherit IDisposable can be called in this manner.

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

I also recommend after the code change is made that you restart your IIS as you might have locking occurring from previous executions, even after the change is made.