-1

I have XML file as follow:

<?xml version="1.0" encoding="ISO-8859-1"?>
<sami>
<title>IN[1]=false</title>
<title>IN[2]=true</title>
<title>OUT[1]=true</title>
<title>OUT[2]=flase</title>
<title>OUT[3]=flase</title>
<title>OUT[4]=flase</title>
<title>$IN[5]=false</title>
</sami>

Question: how to read xml data every second using C#?

I tried the following:

private void Form1_Load(object sender, EventArgs e)
{
    DateTime nextRead;
    Thread thread = new Thread(() =>
    {
        nextRead = DateTime.Now.AddSeconds(1000);
        XDocument doc = XDocument.Load("C:\\Users\\lenovo\\Desktop\\Sxml.xml");
        var result = doc.Descendants("title").ToList();
        textBox1.Text = result[0].Value;
      //  listBox1.Items.Add(result[0].Value);
       // listBox1.Items.Add(result[1].Value);
       // listBox1.Items.Add(result[2].Value);
        Thread.Sleep(Math.Max(0, (DateTime.Now - nextRead).Milliseconds));

    });
    thread.Start();
}
Lennart
  • 9,657
  • 16
  • 68
  • 84
  • your case not clear enough but I think you need to use windows service to read the file every period of time – Ahmed Yousif Sep 02 '18 at 09:37
  • why do u need that ? – J.Memisevic Sep 02 '18 at 09:47
  • i need that because i have GUI in C# and need to read xml data every second and display on the Gui. – smi. kh Sep 02 '18 at 09:52
  • how to use Windows Service in C#??? – smi. kh Sep 02 '18 at 09:55
  • 1
    You cannot use standard xml net methods to parse an xml continuously. When you hit the end of the data and the xml is tag is not closed you will get an exception. You will have to buffer the data and then find the end tags to a start tag and then parse. – jdweng Sep 02 '18 at 10:48
  • 1
    Using a `FileSystemWatcher ` object might be more efficient. Why checking every second, while the file might not have been changed at all? – Bouke Sep 02 '18 at 11:13
  • Do you need to read the XML file every second, or is it enough to read the XML file whenever it changes? – FlashOver Sep 02 '18 at 23:10

2 Answers2

1

You can use Task.Delay to repeat your reading xml file. 1st, create an task method to repeat reading xml file:

static async Task RepeadtReadingXml(int delayMillis, int repeatMillis, CancellationToken ct)

    {

        Console.WriteLine("{0}: Start reading xml file", DateTime.Now);

        await Task.Delay(delayMillis, ct);

        while (true)

        {

            Console.WriteLine("{0}: Reading xml file every 1 sec", DateTime.Now);

            //***************************************************//
            //     Add you logic to read your xml file here      //
            //***************************************************//

            await Task.Delay(repeatMillis, ct);

        }

    }

And call it where you need to repeat your reading:

            var cts = new CancellationTokenSource(); // Work for 5 sec  

            try

            {

                RepeadtReadingXml(2000, 1000, cts.Token).Wait();

            }

            catch (AggregateException ae)

            {

                ae.Handle(e => e is TaskCanceledException);

            }
Nhan Phan
  • 1,262
  • 1
  • 14
  • 32
0

In order to do that, you need to add to your form Timer from toolbox.

Set timer1 interval to 1000 milliseconds. Create event hadnler for timer1.Tick event:

public partial class Form1 : Form
{
    XDocument doc;

    public Form1()
    {
        InitializeComponent();

        timer1.Start();
    }

    private void timer1_Tick(object sender, EventArgs e)
    {
        doc = XDocument.Load("C:\\Users\\Mi\\Desktop\\Sxml.xml");
        var result = doc.Descendants("title").ToList();
        textBox1.Text = result[0].Value;
        listBox1.Items.Add(result[0].Value);
        listBox1.Items.Add(result[1].Value);
        listBox1.Items.Add(result[2].Value);
    }
}
Michał Turczyn
  • 32,028
  • 14
  • 47
  • 69