简体   繁体   中英

XML file to datagridview c#

I am using an api that returns text in XML that I am saving to an XML file. Whenever I am trying to display the information to a datagridview. But I get an error saying the file is already open and being used. Here is the code that receives the text, saves it to the XML and tries to display it to the datagrid.

     using (WebResponse response = request.GetResponse())
        {
            using (Stream stream = response.GetResponseStream())
            {
                using (StreamReader sr99 = new StreamReader(stream))
                {
                    responseContent = sr99.ReadToEnd();
                }
            }
        }
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(responseContent);
        XmlWriterSettings settings = new XmlWriterSettings();
        settings.Indent = true;
        // Save the document to a file and auto-indent the output.
        XmlWriter writer = XmlWriter.Create("ResponseContent.xml", settings);
        doc.Save(writer);



        XmlReader xmlFile = XmlReader.Create(@"C:\Users\Tyler\Documents\Repo\New Trunk\WalmartSmiles\WalmartSmiles\bin\Debug\ResponseContent.xml", new XmlReaderSettings());
        DataSet dataSet = new DataSet();
        //Read xml to dataset
        dataSet.ReadXml("ResponseContent.xml");
        //Pass empdetails table to datagridview datasource
        dataGridView1.DataSource = dataSet.Tables["ns2:feed"];
        //Close xml reader
        xmlFile.Close();
XmlReader xmlFile ;
xmlFile = XmlReader.Create("Product.xml", new XmlReaderSettings());
DataSet ds = new DataSet();
ds.ReadXml(xmlFile);
dataGridView1.DataSource = ds.Tables[0];

Simple way of pass data to dataGridView

Usually when this happens, look for other things in your code that have also opened, read, written, or done anything with that file, and close them!

    // Save the document to a file and auto-indent the output.
    XmlWriter writer = XmlWriter.Create("ResponseContent.xml", settings);
    doc.Save(writer);
    writer.Close();

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