How to prevent this System.IO.IOException when copying a file?

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

There seems to be a lock on file1 ("C: \ CopyDirectoryTest1 \ temp.txt") that creates a few lines above where the error occurs, but I don't know how to do it if that's the case. 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);
            }
        }
    }
}

      

+1


source to share


1 answer


File.Create

returns open FileStream

- you need to close this stream.

Just



using (File.Create(file1)) {}

      

must do the trick.

+13


source







All Articles