Search code examples
c#xmldatagridviewfilesystemwatcher

Read XML files to display data in DataGridView and update UI automatically if XML file is changed using C#


I am trying to read multiple XML files present in one directory (each XML have only one record) and display the records in DataGridView. I want if any of the XML file is updated with new data, its corresponding entry should be automatically updated/refreshed with new updated data in the DataGridView. After doing some search I found that I can use FileSystemWatcher to find if any file is changed, but can anyone please help how can I use it, I am unable to find a good example.

My XML files looks like (please note that there is no root node in it):

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<info>
    <id>001</id>
    <name>xyz</name>
    <salary>1000</salary>
    <phone>1234567890</phone>
</info>

My C# code to read XML and populate gridview is as follows:

using System.Xml;
using System.IO;

namespace XML_Reader
{
    public partial class Form1 : Form
    {        
        string[] fileArray;
        string directory_path = "C:\\Users\\XYZ\\Desktop\\test\\";        

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //Add columns to empty datagridview
            dataGridView1.Columns.Add("id", "id");
            dataGridView1.Columns.Add("name", "name");
            dataGridView1.Columns.Add("salary", "salary");
            dataGridView1.Columns.Add("phone", "phone");

            populateRecords();

        }

        private void populateRecords()
        {
            DataSet ds;
            DataGridViewRow dg_row;

            //Read all XML files and records to datagrid
            fileArray = Directory.GetFiles(directory_path, "MyFiles*.xml");
            foreach (string xmlFile in fileArray_collection)
            {
                //Read the XML from the file                
                ds = new DataSet();
                ds.ReadXml(xmlFile);

                //create new row for datagrid
                dg_row = (DataGridViewRow)dataGridView1.Rows[0].Clone();

                //assign values to cells in the new row
                dg_row.Cells[0].Value = ds.Tables["info"].Rows[0]["id"];
                dg_row.Cells[1].Value = ds.Tables["info"].Rows[0]["name"];
                dg_row.Cells[2].Value = ds.Tables["info"].Rows[0]["salary"];
                dg_row.Cells[3].Value = ds.Tables["info"].Rows[0]["phone"];                

                //Add the new row to datagrid -- THE MOMENT RECORD IS DETECTED
                dataGridView1.Rows.Add(dg_row);

                dataGridView1.FirstDisplayedScrollingRowIndex = dataGridView1.Rows.Count - 1;//This will keep the last added row visible with vertical scrollbar being at bottom.
            }           
        }
    }
}

Solution

  • you have to Implement FileSystemWatcher in your class file.

    new System.IO.FileSystemWatcher m_Watcher = new System.IO.FileSystemWatcher(); 
    

    Then we need to assign it a path and a filter to tell the object where to keep looking.

    m_Watcher.Path = "folder path";
    

    Next we need to tell the watcher what all to look at.

    m_Watcher.Filter = strFilter;
    

    strFilter should be:

    *.* - Watch all files in the Path *.ext - Watch files with the extension ext name.ext - Watch a particular file name.ext

    Next we need to tell the watcher what to look for.

    m_Watcher.NotifyFilter = NotifyFilters.LastAccess | 
                         NotifyFilters.LastWrite | 
                         NotifyFilters.FileName | 
                         NotifyFilters.DirectoryName;
    m_Watcher.IncludeSubdirectories = true; 
    

    Next we need to describe what needs to be done when one of these attributes gets altered.

    m_Watcher.Changed += new FileSystemEventHandler(OnChanged);
    m_Watcher.Created += new FileSystemEventHandler(OnChanged);
    m_Watcher.Deleted += new FileSystemEventHandler(OnChanged);
    m_Watcher.Renamed += new RenamedEventHandler(OnRenamed);
    
    void OnChanged(object sender, FileSystemEventArgs e)
    void OnRenamed(object sender, RenamedEventArgs e)
    

    **Lastly, we need to tell the watcher to do its job - Watch It!!! **

    m_Watcher.EnableRaisingEvents = true;
    

    You can use mentioned link. FileWatcher