简体   繁体   中英

Locking a xml file(located in a server) when the same application(from 2 different computers) is trying to write into it

I have a winapp which writes data into a xml(Data.xml). This xml is my data store.

The winapp will be used by atleast 10 ppl. Sometimes 2 users may simaltaneously import some data and store it into Data.xml(import usually takes 60-100secs). During this period which ever process got the first access on Data.xml must hold a lock on it and the other process must be informed that someone else is importing. (i have not used any threading concepts)

I tried the below :-

FileAttributes fileAttributes = File.GetAttributes(m_sDataXMLPath);
if ((fileAttributes & FileAttributes.ReadOnly) != FileAttributes.ReadOnly)
{
    try
    {
        FileStream currentWriteableFile = File.OpenWrite(m_sDataXMLPath);
        currentWriteableFile.Close();
    }
    catch
    {
        throw; // throw the IO exception so that the other process gets the 
               // exception which is ok with my requirement. 
               // the user just needs to know.
    }
}

The above is working if i run 2 instances of the winapp in one computer, but fails when i am running them on 2 seperate machines!

Please give me some suggestions to lock and then let the other user know someone else is writing into it.

Why are you using GetAttributes()? The file could have ReadOnly attribute and still be readable. Just open the file for write and hold it until writing completes.

using (FileStream file = File.Open("c:\\yourpath\\file.xml", FileMode.Create, FileAccess.Write))
{
... // Here the file is locked
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM