scott_rider 0 Newbie Poster

Thank you in advance. I have intermittent access to a .xml file in App_Data. The file is only used in a portion of the program but there are times when it throws a "...because it is being used by another process." error. I've included everything I could find that is supposed to close the file when it is no longer needed. Does anybody have any ideas how to change the code below that releases the file consistently?

public class XmlDocument : System.Xml.XmlDocument {
  private WebProjectInfo wpi;

  public override void Save(string RelativePath) {
    FileStream fs = null;
      try {
        this.wpi = new WebProjectInfo();
        if (this.wpi.FileExists(RelativePath)) {
          using (fs = this.wpi.GetFileStream(RelativePath)) {
             base.Save(fs);
            };
        } else {
          throw new Exception(RelativePath + " is missing");
        }
      } catch (Exception ex) {
         throw ex;
      } finally {
         fs.Close();
         fs.Dispose();
         fs = null;
         System.GC.Collect();
      }
    }  
}

public class WebProjectInfo {

  // constructors
  public WebProjectInfo() { }

  // value methods
  public bool FileExists(string RelativePath) {
    try{
      FileInfo fi = new FileInfo(this.GetFilePath(RelativePath));
      return fi.Exists;
    } catch (Exception ex) {
      throw ex;
    }
  }

  public FileStream GetFileStream(string RelativePath) {
    try {
      return this.FileExists(RelativePath) == true ?
        new FileStream(GetFilePath(RelativePath), FileMode.Open, FileAccess.ReadWrite, FileShare.None) : null;
    } catch (Exception ex) {
      throw ex;
    }
  }
 
  public string GetFilePath(string RelativePath) {
    return HttpContext.Current.Server.MapPath(RelativePath);
  }

}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.