I trying to develop a Windows Forms application for reading and writing a very large XML file. I have two buttons, 1) for writing an XML file, ** and 2) reading an XML file. When I click on the write XML button my winForm application is hanging. No other operation is allowed to be performed while writing to the XML file, but I want to read and write into same XML file.
For reading
void btnReading_Click(object sender, EventArgs e)
{
strXpathQuery = "/AppXmlLogWritter/LogData[substring(LogDateTime, 1, 8) >='" +
dateTimePickerFromDate.Value.ToString("yyyyMMdd") +
"' and substring(LogDateTime, 1, 8) <='" +
dateTimePickerToDate.Value.ToString("yyyyMMdd") +
"']";
XmlElement objXmlRoot = null;
XmlNodeList objxmlNodeList = objXmlRoot.SelectNodes(strXpathQuery);
}
void BindData(objxmlNodeList);
{
BindData(XmlNodeList objxmlNodeList)
DataTable dataTable = new DataTable();
dataTable = XmlNodeListToDataTable(objxmlNodeList, new string[] { "LogID", "LogDateTime"});
lstViewInfo.View = View.Details;
lstViewInfo.Clear();
lstViewInfo.Columns.Add("LogID", Convert.ToInt32(lstViewInfo.Width * 0.20));
lstViewInfo.Columns.Add("LogDateTime", Convert.ToInt32(lstViewInfo.Width * 0.20));
ListViewItem objListViewitem = null;
for (int i = 0; i < dataTable.Rows.Count; i++)
{
objListViewitem = new ListViewItem();
objListViewitem.Text = dataTable.Rows[i]["LogID"].ToString();
objListViewitem.SubItems.Add(dataTable.Rows[i]["LogDateTime"].ToString());
lstViewInfo.Items.Add(objListViewitem);
}
}
For writing
void button1_Click(object sender, EventArgs e)
{
Mutex objMutex = new Mutex(false, @"Global\MySharedLog");
XmlDocument xmlDoc = new XmlDocument();
string currentDateTime = DateTime.Now.ToString("yyyyMMddHHmmss");
XmlElement newelement = xmlDoc.CreateElement("LogData");
XmlElement xmlLogID = xmlDoc.CreateElement("LogID");
XmlElement xmlLogDateTime = xmlDoc.CreateElement("LogDateTime");
int randomNumber = random.Next(9999);
xmlLogID.InnerText = _logIDPrefix + currentDateTime + DateTime.UtcNow.Ticks + randomNumber;
xmlLogDateTime.InnerText = currentDateTime;
newelement.AppendChild(xmlLogID);
newelement.AppendChild(xmlLogDateTime);
try
{
objMutex.WaitOne();
if (!File.Exists(_logFilePath))
{
File.WriteAllText(
_logFilePath,
"<?xml version='1.0' encoding='utf-8' standalone='yes'?>\r\n<AppXmlLogWritter><objMutex></objMutex></AppXmlLogWritter>");
}
using (FileStream fileStream = new FileStream(_logFilePath,
FileMode.OpenOrCreate,
FileAccess.ReadWrite,
FileShare.ReadWrite))
{
xmlDoc.Load(fileStream);
xmlDoc.DocumentElement.AppendChild(newelement);
fileStream.SetLength(0);
xmlDoc.Save(fileStream);
}
}
finally
{
objMutex.ReleaseMutex();
}
}