loviji
loviji

Reputation: 13080

problem while writing data into xml, when event occured

I'm trying to write a little software for logging data, if any type of file created in directory A.

I use FileSystemWatcher class to get information about file creation in folder A. There are many subfolder in folder A. And many users can create file in this directory in one time.

I use XML data to save log data.

XmlTextReader reader = new XmlTextReader(FILE_NAME);
XmlDocument doc = new XmlDocument();
doc.Load(reader);
reader.Close();
XmlNode currNode;

XmlDocumentFragment docFrag = doc.CreateDocumentFragment();
docFrag.InnerXml = "<item>" +
"<path>" + fileName + "</path>" +
"<created>0</created>" +
"<date>" + DateTime.ParseExact(DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss"), "dd.MM.yyyy HH:mm:ss", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None).ToString() + "</date>" +
"</item>";
// insert the availability node into the document
currNode = doc.DocumentElement;
currNode.InsertAfter(docFrag, currNode.LastChild);
//save the output to a file
doc.Save(FILE_NAME);

But sometimes while occurs watcher.Created += new FileSystemEventHandler(OnChanged);, data about file creation is not inserted to XML file.

So, is it possible if file opened for data writing, and it's locked for new dataWrite file document not saved? and how to fix this.

Upvotes: 2

Views: 271

Answers (3)

Ramon Araujo
Ramon Araujo

Reputation: 1738

You are in front of a beauty computer problem, please read a bit about the Dining Philosophers problem in http://en.wikipedia.org/wiki/Dining_philosophers_problem .

You can "lock" a file just setting its attribute to ReadOnly

I mean, when you are going to write, you check if "ReadOnly" is set. In that case

System.IO.File.SetAttributes("pathtofile\filename.ext", FileAttributes.ReadOnly);

After writing, please remove the attribute.

A more complex solution could be the use of semaphores, thus controlling yourself the files that are being accessed. You can find a hint here in StackOverflow:

Problem with using Semaphore to protect queue

Also, you can use this link as a hint to really lock files:

How to lock file

Hope that helps,

Upvotes: 2

G&#244;T&#244;
G&#244;T&#244;

Reputation: 8053

If you need to log data very often, you should either write to database instead of writing to a file or use buffering.

Upvotes: 0

Restuta
Restuta

Reputation: 5903

Seems that sometimes you open file several times and between this operations file is in different states, so when you write it you just overwrite some data written before. I propose you to collect changes in Queue and write them to the file sequentially.

Upvotes: 1

Related Questions