当我运行以下代码来测试复制目录时,在调用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);
}
}
}
}
答案 0 :(得分:13)