File used by another C # process

I work in a WPF application, I want to create an XML file and load it simultaneously in a window. At the moment, my code is working fine, but when I want to load the created file in a window, it tells me that the File is being used by another process. Here is my code

var now = DateTime.Now;
        var timestamp = "" + now.Hour + now.Minute + now.Second;
        string sb = "test";
        var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        File.WriteAllText(string.Format("{0}\\{1}.xml", path, timestamp), sb);
        File.AppendText(string.Format("{0}\\{1}.xml", path, timestamp));


        XmlDocument XMLdoc = new XmlDocument();
        try
        {
            XMLdoc.Load(string.Format("{0}\\{1}.biml", path, timestamp));
        }
        catch (XmlException)
        {
            MessageBox.Show("The XML file is invalid");
            return;
        }


        vXMLViwer.xmlDocument = XMLdoc;
+4
source share
1 answer

File.AppendTextwill open the file and return a stream that you can use to add data. Since you are not using the return value of such a method, this means that you will not close the stream until the garbage collector decides to hit later.

, File.AppendText ( , ?). , , , File.AppendAllText.

+5

Source: https://habr.com/ru/post/1629164/


All Articles