Question

When I run the following code to test copying a directory, I get a System.IO.IOException when fileInfo.CopyTo method is being called. The error message is: "The process cannot access the file 'C:\CopyDirectoryTest1\temp.txt' because it is being used by another process."

It seems like there's a lock on file1 ("C:\CopyDirectoryTest1\temp.txt") which is created a few lines above where the error is occurring, but I don't know how to release this if so. Any ideas?

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);
            }
        }
    }
}
Was it helpful?

Solution

File.Create returns an open FileStream - you need to close that stream.

Just

using (File.Create(file1)) {}

should do the trick.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top