复制文件时如何防止此System.IO.IOException?

时间:2008-11-06 07:10:12

标签: c# io ioexception

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

1 个答案:

答案 0 :(得分:13)

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

只需

using (File.Create(file1)) {}

应该这样做。