当我运行以下代码来测试复制目录时,我在调用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); } } } }
Jon Skeet.. 13
File.Create
返回打开FileStream
- 您需要关闭该流.
只是
using (File.Create(file1)) {}
应该做的伎俩.
File.Create
返回打开FileStream
- 您需要关闭该流.
只是
using (File.Create(file1)) {}
应该做的伎俩.