0

I'm developing an add-on for Excel in C# which includes an RTD server. Because we do not have a SQL database yet, I must use an XML file to store the data.

The XML file is updated via a C# function used in Excel on one side. On the other side, multiple users must be able to retrieve this data in real time.

When I'm running both functions (update and read the XML file), the write function crashes from time to time with the error file being usee by another process.

The write function:

string _dataPath = Path.Combine(xllDir, "Test.xml");

        XmlDocument xmlDoc = new XmlDocument();

        xmlDoc.Load(_dataPath);

        XmlNode node = xmlDoc.SelectSingleNode(Data_Type.ToUpper() + "/" + Ticker.ToUpper() + "/" + Data.ToUpper() + "/VALUE");

        node.InnerXml = Convert.ToString(Value);

        XmlNode node_update = xmlDoc.SelectSingleNode(Data_Type.ToUpper() + "/" + Ticker.ToUpper() + "/" + Data.ToUpper() + "/LAST_UPDATE");
        node_update.InnerXml = Convert.ToString((DateTime.Now).TimeOfDay);

        xmlDoc.Save(_dataPath);

and read function:

 _xml.Load(topic.FileName);
        XmlNode node = _xml.SelectSingleNode("//" + topic.Ticker);
        topic.Value = node.InnerText;

I can't see how to sort this out, so any idea will be more than welcome.

zondo
  • 19,901
  • 8
  • 44
  • 83
julien
  • 11
  • 2

2 Answers2

1

I just found an easy answer:

FileStream fs = new FileStream(FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
         _xml.Load(fs);
         fs.Close();
         XmlNode node = _xml.SelectSingleNode("//" + Ticker);
         return node.InnerText;

In this way, for both read and write functions, nothing crashes at all.

zondo
  • 19,901
  • 8
  • 44
  • 83
julien
  • 11
  • 2
0

You cannot as far as I know. Define a class that maps you xml file (e.g. public class Ticker). Instantiate an object of that class when you are updating the xml file:

node_update.InnerXml = Convert.ToString((DateTime.Now).TimeOfDay);
var ticker = new Ticker();
ticker.tickerValue = node_update.InnerText;

and access the new data via that object:

topic.Value = this.ticker.tickerValue;  

Note: You can use observer pattern for you ticker class and update it whenever you're updating the xml file.

Kamyar
  • 18,639
  • 9
  • 97
  • 171