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.
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,