1
當我運行下面的代碼來測試拷貝目錄時,當調用fileInfo.CopyTo方法時,我得到一個System.IO.IOException。錯誤消息是:「進程無法訪問文件'C:\ CopyDirectoryTest1 \ temp.txt',因爲它正在被另一個進程使用。」如何在複製文件時防止此System.IO.IOException?
看起來似乎有一個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);
}
}
}
}