当我运行以下代码来测试复制目录时,在调用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);
            }
        }
    }
}
有帮助吗?

解决方案

File.Create 返回一个打开的 FileStream - 您需要关闭该流。

只需

using (File.Create(file1)) {}

应该这样做。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top