gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:00:50 24 4
gpt4 key购买 nike

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

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

  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它在文件上设置的权限。

关于c# - 无法访问该文件,因为它正被另一个进程使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10177213/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com