Skip to main content
 首页 » 编程设计

c#之无法访问该文件,因为它正被另一个进程使用

2024年02月23日16bonelee

我知道,这个问题已经在很多地方被反复问过了。但是我已经尝试用谷歌搜索它并检查该站点以获取解决方案,但仍然不足。即使使用了所有建议的解决方案,我仍然遇到这个问题。

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

  1. ProgramA - 功能:不断更新源文件(txt)
  2. ProgramB* - 功能:不断将源文件复制到目标位置。

对于 ProgramB,我想模拟执行 ctrl+c 操作。因此,我正在尝试存档,以便我可以更新文件,运算符(operator)也可以复制它。

这是我到目前为止尝试过的方法。下面是测试功能的示例程序。

程序A

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(); 
    } 
} 

程序B

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(); 
        } 
    } 
} 

请您参考如下方法:

而不是使用 File.Copy , 尝试使用 FileStream并自己复制这些位。上面的代码会报错,如File.Copy没有指定什么 FileShare它在文件上设置的权限。