简体   繁体   中英

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". 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.

How can I fix this? Any ideas or suggestions will be a big help. Thanks

Here is the filesystemwatcher code

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

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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