简体   繁体   English

进程无法访问文件,因为它被另一个进程使用

[英]c# - Process cannot access file because it is used by another process

This is the scenario, I have an application that overwrites an xml file every 2secs. 在这种情况下,我有一个应用程序,每2秒会覆盖xml文件。 And then I have this c# application, that reads this file every 1-2secs. 然后,我有了这个C#应用程序,它每1-2秒读取一次此文件。 this process runs fine, but there are times when i get the error saying, 这个过程运行良好,但是有时我会收到错误消息,

Process cannot access file because it is used by another process 进程无法访问文件,因为它被另一个进程使用

I am using xmldocument.load to open and read the xml file. 我正在使用xmldocument.load打开和读取xml文件。

What can i do to solve this issue? 我该怎么做才能解决这个问题? I have tried running on different machines, and this is absolutely random, as on my machine, it ran for 6 hours before the error, on another machine, 我尝试在不同的计算机上运行,​​这绝对是随机的,因为在我的计算机上,它在错误发生之前已经在其他计算机上运行了6个小时,

Coz my c# program will continue reading this file, unless the user click a button to stop the data logging process 因为我的c#程序将继续读取该文件,除非用户单击一个按钮以停止数据记录过程

As i want the program to continue running as long as the user doesn't stop it. 因为我希望程序只要用户不停止就可以继续运行。 Please help 请帮忙

Please tell have you tried reading XmlDocument content using FileStream variable which was instantiated with appropriate FileMode and FileAccess and FileShare parameters using specialy designated constructor . 请告诉您您是否尝试使用FileStream变量读取XmlDocument内容,该变量已使用特殊指定的构造函数通过适当的FileMode以及FileAccessFileShare参数实例化。 You can load content of XmlDocument using implementation of Load method which takes appropriately openned (for write with share of read access of vice versa) filestream as parameter. 您可以使用Load方法的实现来加载 XmlDocument的内容,该方法将适当打开的文件流(用于共享写入,反之亦然)以文件流为参数。

Please try using following code for writing to file: 请尝试使用以下代码写入文件:

XmlDocument xmlDocument = new XmlDocument();
using (FileStream fileStream = new FileStream("C:\\test.xml", FileMode.Append, FileAccess.Write, FileShare.Read))
{
    xmlDocument.Load(fileStream);
}

and following code for reading from file: 以及以下用于从文件读取的代码:

XmlDocument xmlDocument = new XmlDocument();
int attempts = 5;
Exception cannotReadException = null;
while (attempts > 0)
{
    try
    {
        using (FileStream fileStream = new FileStream("C:\\test.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            xmlDocument.Load(fileStream);
            attempts = 0;
        }
    }
    catch (Exception exception)
    {
        cannotReadException = exception;
        System.Threading.Thread.Sleep(100);
        attempts--;
    }
}

if (cannotReadException != null)
{
    throw cannotReadException;
}

You cannot read from file when that another application write to that same file, if you have develop both applications I would reccomend real database instead XML file. 当另一个应用程序写入同一文件时,您将无法从文件中读取文件,如果您同时开发了这两个应用程序,我将推荐使用真正的数据库而不是XML文件。 For excample SQLite . 对于示例SQLite

But if you won't to use xml files you can catch exception that XmlDocument.Load throws and try to read again hoping that other process is done with writting 但是,如果您不使用xml文件,则可以捕获XmlDocument.Load引发的异常,然后尝试再次读取以希望其他过程已通过写入完成

The file is either still marked in use by your operating system, in use by another computer or in use by your virus scanner at times and isn't freed fast enough for your program. 该文件有时仍被标记为操作系统正在使用,另一台计算机正在使用或病毒扫描程序正在使用,并且对于程序而言,释放的速度不够快。 You should either insert a small timeout/delay or catch the exception using a try .. catch and retry after, again, a small delay. 您应该插入一个小的超时/延迟,或者使用try .. catch捕获异常,然后在短暂的延迟后再次尝试。

When you use a timer you should stop timer when you process on a file until you finish: 使用计时器时,在处理文件时应停止计时器,直到完成:

private void timer_Tick(object sender, EventArgs e)
{
  try
  {
    timer.Stop();
    //read write whatever ...
  }
  catch(){}  
  timer.start(); 
}

To avoid conflicts do your overwriting like this: 为了避免冲突,请按照以下步骤进行覆盖:

  • write the new XML to a temporary file in same location as old XML 将新XML写入与旧XML相同位置的临时文件中
  • rename new file to old file 将新文件重命名为旧文件

on UNIX file systems this will avoid problem of read attempts failing during the write. 在UNIX文件系统上,这将避免在写入过程中读取尝试失败的问题。 Not sure about windows, but should work. 不确定Windows,但应该可以。

To expand on what others have suggested, here is an example of how you may implement using a try catch block to resolve the conflict: 为了扩展其他人的建议,下面是一个示例,说明如何使用try catch块解决冲突:

private XmlDocument OpenXML(string filename, int retryCount = 0)
{
    XmlDocument retval = new XmlDocument();

    try
    {
        retval.Load(filename);
    }
    catch
    {
        if (retryCount < 5)
        {
            retval = OpenXML(filename, retryCount + 1);
        }
        else
        {
            return null;
        }
    }

    return retval;
}

In the catch you could add a pause if needed, or increase the number of retry attempts / deal with it differently when the maximum number of attempts has been reached. 如果需要,您可以在捕获中添加一个暂停,或者在达到最大尝试次数后增加重试次数/以不同的方式进行处理。

As already suggested, you could implement a simple wait-for-x-(milli)seconds-and-retry approach. 正如已经建议的那样,您可以实现一种简单的x毫秒等待时间,然后重试。

If you're on Windows and have access to the sources of both programs, you could use the native Win32 functions to create a semaphore to regulate access to the file. 如果您使用的是Windows,并且可以访问这两个程序的源代码,则可以使用本机Win32函数来创建信号量,以调节对文件的访问。 See this page for more details. 有关更多详细信息,请参见此页面。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 C#-无法访问文件“ X”,因为它已被另一个进程使用 - C# - Cannot access the file “X” because it is used by another process c#无法访问文件,因为它正被另一个进程使用 - c# Cannot access file because it is being used by another process C# File.ReadAllText 进程无法访问该文件,因为它正被另一个进程使用 - C# File.ReadAllText The process cannot access the file because it is being used by another process IOException:该进程无法访问文件“文件路径”,因为它正在被C#控制台应用程序中的另一个进程使用 - IOException: The process cannot access the file 'file path' because it is being used by another process in Console Application in C# 生成 txt 文件时出现“进程无法访问文件 --- 因为它正被另一个进程使用” C# - "The process cannot access the file --- because it is being used by another process" when making txt file C# 该进程无法访问文件&#39;D:.txt&#39;,因为它正在由c#中的另一个进程使用 - The process cannot access the file 'D:.txt' because it is being used by another process in c# C#XMLDocument保存 - 进程无法访问该文件,因为它正由另一个进程使用 - C# XMLDocument Save - Process cannot access the file because it is being used by another process C#进程无法访问文件“ XYZ”,因为它正在被另一个进程使用 - C# The process cannot access file 'XYZ' because it is being used by another process 错误:Visual Studio c# 中的“进程无法访问该文件,因为它正被另一个进程使用” - Error: 'The process cannot access the file because it is being used by another process' in Visual Studio c# C# WriteLine :该进程无法访问该文件,因为它正在被另一个进程使用 - C# WriteLine : The process cannot access the file because it is being used by another process
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM