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

时间:2012-04-16 15:36:55

标签: c#

我知道,这个问题已在很多地方反复提出过。但我试图谷歌它并检查这个网站的解决方案,但仍然很短。即使使用了所有建议的解决方案,我仍然遇到这个问题。

基本上,我有两个独立的程序。每个程序的功能如下所示。

  1. ProgramA - 功能:不断更新源文件(txt)
  2. ProgramB * - 功能:不断将源文件复制到目标位置。
  3. 使用ProgramB,我想模拟执行ctrl + c操作。因此,我试图存档在哪里,我可以更新文件,操作员也可以复制它。

    这是我到目前为止所尝试的内容。下面是测试功能的示例程序。

    ProgramA

    static void Main(string[] args)
    {
        // just prepare the data
        List<string> tempList = new List<string>();
        for(int i = 0; i < 50000; i++)
        {
            tempList.Add(string.Format("xxx_{0}", i.ToString()));
        }
    
        try
        {
            // just to simulate constart update
            for (int j = 0; j < 20000; j++)
            {
                using (FileStream file = new FileStream(tmpFilePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
                {
                    using (StreamWriter sw = new StreamWriter(file))
                    {
                        foreach (string tmpName in tempList)
                        {
                            sw.WriteLine(tmpName);
                        }
                        sw.Close();
                    }
                    file.Close();
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            Console.ReadKey();
        }
    }
    

    ProgramB

    static void Main(string[] args)
    {
        string source = @"C:\temp\test.txt";
        string dest = @"C:\temp\dest\test.txt";
        while (true)
        {
            try
            {
                File.Copy(source, dest, true);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Console.ReadKey();
            }
        }
    }
    

3 个答案:

答案 0 :(得分:2)

请尝试使用File.Copy并自行复制这些内容,而不是使用FileStream。上面的代码会出错,因为File.Copy没有指定它在文件上设置的FileShare权限。

答案 1 :(得分:1)

这应该是一个评论,但它太长了。它更像是一个设计建议,而不是一个编码答案。

我假设这两个程序都在计时器上,或者在FileSystemWatcher上,这意味着缺乏可预测性。您无法保证何时调用程序A或何时调用程序B,与执行读/写操作所需的时间相关。

换句话说,由于设计中固有的缺乏控制,您无法预测文件何时被锁定。

如果可能的话,我会把这两个程序结合起来。实际上,我想你想要的是在程序A完成写入后立即复制文件(程序b功能)。没有(显而易见的)原因你不能对它进行编码,以便程序A在写入文件后立即复制文件。

如果缺乏可预测性是问题的根源,请消除不可预测性。

答案 2 :(得分:1)

如果这两个程序都在同一台计算机上运行,​​您可以使用名为Mutex并在写入时锁定并复制该文件。

所以在程序A中你要添加

using (Mutex m = new Mutex(false,"MyMutex"))
{
    m.WaitOne();
    // Your file writing code
    m.ReleaseMutex();
}

围绕文件复制代码做同样的事情。