Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/314.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 当同一应用程序(来自两台不同的计算机)试图写入xml文件时,锁定xml文件(位于服务器中)_C#_.net_Winforms - Fatal编程技术网

C# 当同一应用程序(来自两台不同的计算机)试图写入xml文件时,锁定xml文件(位于服务器中)

C# 当同一应用程序(来自两台不同的计算机)试图写入xml文件时,锁定xml文件(位于服务器中),c#,.net,winforms,C#,.net,Winforms,我有一个winapp,它将数据写入xml(data.xml)。这个xml是我的数据存储 winapp将被至少10个ppl使用。有时两个用户可能同时导入一些数据并将其存储到data.xml中(导入通常需要60-100秒)。在此期间,哪个进程获得了对Data.xml的第一次访问权,必须对其进行锁定,并且必须通知另一个进程其他人正在导入。(我没有使用任何线程概念) 我尝试了以下方法:- FileAttributes fileAttributes = File.GetAttributes(m_sData

我有一个winapp,它将数据写入xml(data.xml)。这个xml是我的数据存储

winapp将被至少10个ppl使用。有时两个用户可能同时导入一些数据并将其存储到data.xml中(导入通常需要60-100秒)。在此期间,哪个进程获得了对Data.xml的第一次访问权,必须对其进行锁定,并且必须通知另一个进程其他人正在导入。(我没有使用任何线程概念)

我尝试了以下方法:-

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.
    }
}
如果我在一台计算机上运行两个winapp实例,但在两台不同的计算机上运行它们时失败,则上述方法有效


请给我一些关于锁定的建议,然后让其他用户知道有人正在写入它。

为什么要使用GetAttributes()?该文件可能具有ReadOnly属性,并且仍然可读。只需打开文件进行写入,并将其保持到写入完成

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

文件已创建,filemode.Open,如果我使用fileaccess.write,那么xmldoc.load会抛出一个异常,说明此进程已在使用中。我应该加载“文件”而不是以前的路径吗?这通常取决于FileAccess的属性,会给我“流不可读”或“流不可写”异常。。谢谢你的回复