read and close xml file

0

I am using this method to select a value from an xml file.

The problem is that this xml file is used by another program, that program tells me that the file has already been opened and does not proceed to perform the function. What I need is that when the method takes the value of the xml file, I close it.

This is the method:

private String getArticleID()

        {
            if (!IsFileLocked(@Properties.Settings.Default.fxml))
            {
                try
                {
                    var inStream = new FileStream(@Properties.Settings.Default.fxml, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    XmlDocument documento = new XmlDocument();
                    //string xmlText = File.ReadAllText(xmlpath);
                    //documento.LoadXml(xmlText);
                    documento.Load(inStream);
                    //  documento.LO
                    XmlNode child = documento.SelectSingleNode("Machine/Article/ArticleID");
                    if (child != null)
                    {
                        String val = child.InnerText;
                        return val;
                    }
                    }
                catch (Exception ex)
                {
                    Console.Beep();
                    fw.evenLog.WriteEntry("Error_GetArticle " + ex.Message, EventLogEntryType.Error);
                    fw.ErrLog += ex.Message + Environment.NewLine + "\n\r";
                }
            }
           return "#";
        }
    
asked by Ronald López 21.05.2018 в 22:18
source

1 answer

0

You should use a using block when opening the stream . This block of code that you make is a Close and a Dispose of said stream .

private String getArticleID()
{
    if (!IsFileLocked(@Properties.Settings.Default.fxml))
    {
        try
        {
            using (var inStream = new FileStream(@Properties.Settings.Default.fxml, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                XmlDocument documento = new XmlDocument();
                //string xmlText = File.ReadAllText(xmlpath);

                //documento.LoadXml(xmlText);
                documento.Load(inStream);
                //  documento.LO
                XmlNode child = documento.SelectSingleNode("Machine/Article/ArticleID");
                if (child != null)
                {
                    String val = child.InnerText;
                    return val;
                }
            }
        }
        catch (Exception ex)
        {
            Console.Beep();
            fw.evenLog.WriteEntry("Error_GetArticle " + ex.Message, EventLogEntryType.Error);
            fw.ErrLog += ex.Message + Environment.NewLine + "\n\r";
        }
    }
    return "#";
}
    
answered by 22.05.2018 в 00:46