using FileCounter.Core; using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; using System.Xml; using System.Xml.Serialization; namespace FileCounter { public partial class Form1 : Form { // The "name" must be unique to your app to avoid collisions. EventWaitHandle waitHandle = new EventWaitHandle(true, EventResetMode.AutoReset, "APPNAME_FILENAME_WAITHANDLE_123"); //const string filepath = "..\\..\\..\\..\\sample.xml"; const string filepath = "..\\..\\CounterTest.xml"; EANCODING obj; public Form1() { InitializeComponent(); } private void btnIncreaseCounter_Click(object sender, EventArgs e) { waitHandle.WaitOne(); // Create an XML deserialiser & read the file stream of the XML file into it. XmlSerializer serialiser = new XmlSerializer(typeof(EANCODING)); using (StreamReader reader = new StreamReader(filepath)) { obj = (EANCODING)serialiser.Deserialize(reader); // Increment the current counter obj.CURRENTCOUNTER.value++; Console.WriteLine($"New counter: {obj.CURRENTCOUNTER.value}"); } // Serialise the obj back to XML and write it back to the file. using (StreamWriter writer = new StreamWriter(filepath)) { using (var xmlWriter = XmlWriter.Create(writer, new XmlWriterSettings { Indent = true })) serialiser.Serialize(xmlWriter, obj); } waitHandle.Set(); } } }