当我运行以下代码来测试复制目录时,我在调用 fileInfo.CopyTo 方法时收到 System.IO.IOException。错误消息是:“该进程无法访问文件 'C:\CopyDirectoryTest1\temp.txt',因为它正被另一个进程使用。”
似乎 file1 ("C:\CopyDirectoryTest1\temp.txt") 上有一个锁,它是在发生错误的几行上方创建的,但如果是这样,我不知道如何释放它。有任何想法吗?
using System;
using System.IO;
namespace TempConsoleApp
{
class Program
{
static void Main(string[] args)
{
string folder1 = @"C:\CopyDirectoryTest1";
string folder2 = @"C:\CopyDirectoryTest2";
string file1 = Path.Combine(folder1, "temp.txt");
if (Directory.Exists(folder1))
Directory.Delete(folder1, true);
if (Directory.Exists(folder2))
Directory.Delete(folder2, true);
Directory.CreateDirectory(folder1);
Directory.CreateDirectory(folder2);
File.Create(file1);
DirectoryInfo folder1Info = new DirectoryInfo(folder1);
DirectoryInfo folder2Info = new DirectoryInfo(folder2);
foreach (FileInfo fileInfo in folder1Info.GetFiles())
{
string fileName = fileInfo.Name;
string targetFilePath = Path.Combine(folder2Info.FullName, fileName);
fileInfo.CopyTo(targetFilePath, true);
}
}
}
}