简体   繁体   English

使用FileSystemWatcher中的XDocument.Load加载xml文件。 错误“进程无法访问文件..etc”

[英]Load a xml file using XDocument.Load from FileSystemWatcher. Error “The process cannot access the file..etc”

Is there a way to fix the error "The process cannot access the file..etc". 有没有办法纠正错误“该进程无法访问该文件.etc”。 The flow is that the filesystemwatcher will watch for a xml file when I detects a xml file i need to read a specific node from the xml file. 流程是,当我检测到我需要从xml文件读取特定节点的xml文件时,filesystemwatcher将监视xml文件。

How can I fix this? 我怎样才能解决这个问题? Any ideas or suggestions will be a big help. 任何想法或建议都会有很大帮助。 Thanks 谢谢

Here is the filesystemwatcher code 这是filesystemwatcher代码

private void fileSystemWatcher_Created(object sender, System.IO.FileSystemEventArgs e)
    {
        try
        {
            string type = GetType(e.FullPath).ToUpper();
            if (type == "CC")
            {
                if (Global.pc_flag)
                {
                    ProcessPC(e.FullPath);
                }
                else if (Global.mw_flag)
                {
                    ProcessMW(e.FullPath);
                }
                else
                {
                    ProcessXML(e.FullPath);
                }
            }
            else if (type == "GC")
            {
                ProcessMW(e.FullPath);
            }
            //Process(e.FullPath);
        }
        catch(Exception ex)
        {
            error++;
            lblErrors.Text = error.ToString();
            MessageBox.Show(ex.Message);
        }
    }

Here what contains of GetType 此处包含GetType

private string GetType(string file)
    {
        string type = string.Empty;
        using (var stream = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            var request = XDocument.Load(stream);
            var get_command = from r in request.Descendants("Transaction")
                              select new
                              {
                                  Type = r.Element("Type").Value
                              };

            foreach (var c in get_command)
            {
                type = c.Type;
            }
        }
        return type;
    }

You don't use your stream in code and while the stream is open you can not access the file in XDocument.Load(file) 您不会在代码中使用stream ,并且在流打开时无法访问XDocument.Load(file)

private string GetType(string file)
{
    string type = string.Empty;
    var request = XDocument.Load(file);
    var get_command = from r in request.Descendants("Transaction")
                      select new
                      {
                          Type = r.Element("Type").Value
                      };
    foreach (var c in get_command)
    {
        type = c.Type;
    }
    return type;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM