当使用LINQ to xml读取和写入xml文件时;进程无法访问该文件,因为它正被另一个进程“使用”;

本文关键字:文件 xml 进程 因为 使用 另一个 访问 读取 LINQ to | 更新日期: 2023-09-27 18:24:41

在使用LINQ to xml读取和写入xml文件时,我面临"进程无法访问该文件,因为它正被另一个进程使用"

异常日志为

2014年9月25日下午4:49:03异常:类公共,方法名称:CreateXML。异常进程无法访问文件"D:''Program Files''Default"公司名称''Setup''Settings''Settings.xml",因为它正被另一个过程。

请建议一些方法。

以下是我的代码:

public void CreateXML(string toEmail, out int notificationCount, out string email, bool IsFirstTime = false)
{
    notificationCount = 0;
    email = string.Empty;
    try
    {
        string path = String.Format(@"{0}Settings", AppDomain.CurrentDomain.BaseDirectory);
        string filePath = path + "''Settings.xml";
        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
        if (!IsFirstTime)
        {
            if (File.Exists(filePath))
            {
                XDocument xmlDoc = XDocument.Load(filePath);
                if (xmlDoc.Elements("Filters").Count() > 0)
                {
                    XElement doc = new XElement(
                                                  new XElement("Filter",
                                                      new XElement("ToEmail", toEmail),
                                                      new XElement("Date", DateTime.Now.ToString())
                                                      )
                                                  );
                    xmlDoc.Element("Filters").Add(doc);
                    try
                    {
                        xmlDoc.Save(filePath);
                    }
                    catch (Exception ex)
                    {
                        string x = ex.Message;
                    }
                }
                else
                {
                    CreateXmlNodes(toEmail, filePath);
                }
            }
            else
            {
                CreateXmlNodes(toEmail, filePath);
            }
        }
        if (File.Exists(filePath))
        {
            XDocument xmlDoc = XDocument.Load(filePath);
            notificationCount = GetEmailAndNotificationCount(notificationCount, filePath, xmlDoc, out email);
        }
    }
    catch (Exception ex)
    {
        new Logging().LogException("Class Common, Method Name: CreateXML. Exception" + ex.Message);
    }
}
private static int GetEmailAndNotificationCount(int notificationCount, string filePath, XDocument xmlDoc, out string email)
{
    email = string.Empty;
    try
    {
        StringBuilder sb = new StringBuilder();
        XElement xdoc = XElement.Load(filePath);
        if (xdoc.Elements("Filter").Count() > 0)
        {
            var data = (from p in xdoc.Descendants("Date").Where(x => Convert.ToDateTime(x.Value) > DateTime.Now.AddDays(-1))
                        select p).ToList().Count;
            NotificationCount = notificationCount = data;
            var emails = (from p in xdoc.Descendants("Filter").Where(x => Convert.ToDateTime(x.Element("Date").Value) > DateTime.Now.AddDays(-1))
                          select p.Element("ToEmail").Value).Distinct().Where(x => !string.IsNullOrEmpty(Convert.ToString(x))).ToList();
            if (emails.Count > 0)
            {
                emails.ForEach(x => sb.Append(x.ToString()).Append("'n"));
            }
            EmailsToDisplay = email = sb.ToString();
            xmlDoc.Descendants("Filter").Where(x => Convert.ToDateTime(x.Element("Date").Value) < DateTime.Now.AddDays(-2)).Remove();
            try
            {
                xmlDoc.Save(filePath);
            }
            catch (Exception ex)
            {
                new Logging().LogException("Class Common, Method Name: GetEmailAndNotificationCount. Exception" + ex.Message);
            }
        }
    }
    catch (Exception ex)
    {
        new Logging().LogException("Class Common, Method Name: GetEmailAndNotificationCount. Exception" + ex.Message);
        email = string.Empty;
        return 0;
    }
    return notificationCount;
}
private static void CreateXmlNodes(string toEmail, string filePath)
{
    XDocument doc = new XDocument(
                                  new XElement("Filters",
                                    new XElement("Filter",
                                        new XElement("ToEmail", toEmail),
                                        new XElement("Date", DateTime.Now.ToString())
                                        )
                                    ));
    try
    {
        doc.Save(filePath);
    }
    catch (Exception ex)
    {
        new Logging().LogException("Class Common, Method Name: CreateXmlNodes. Exception" + ex.Message);
    }
}

堆栈跟踪:

"StackTrace:at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost) at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy)at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role,Type ofObjectToReturn)
   at System.Xml.XmlTextReaderImpl.FinishInitUriString()
   at System.Xml.XmlTextReaderImpl..ctor(String uriStr, XmlReaderSettings settings, XmlParserContext context, XmlResolver uriResolver)
   at System.Xml.XmlReaderSettings.CreateReader(String inputUri, XmlParserContext inputContext)
   at System.Xml.XmlReader.Create(String inputUri, XmlReaderSettings settings, XmlParserContext inputContext)
   at System.Xml.Linq.XDocument.Load(String uri, LoadOptions options)
   at BLLayer.Common.Common.CreateXML(String toEmail, Int32& notificationCount, String& email, Boolean IsFirstTime)"

当使用LINQ to xml读取和写入xml文件时;进程无法访问该文件,因为它正被另一个进程“使用”;

您可能需要在第二次加载()XDocument之前关闭()它。