Share via


FileInfo locks files. How to unlock them

Question

Monday, June 27, 2016 5:57 AM

Hi 

I have the following code

DirectoryInfo dInfo1 = new DirectoryInfo(@".\Output\DirectoryInfo");

...

// Here i create some subdirectories and files in the Output\DirectoryInfo

 // Creating SubDirectories
 DirectoryInfo subdir1 = dInfo1.CreateSubdirectory("Sub1");

...

// Now create some files
                string path = subdir1.FullName + @"\test.txt";
                FileInfo f1 = new FileInfo(path);
                f1.Create();

Console.WriteLine("Listing All Files in SubDirectories");
 IEnumerable<FileInfo> files = dInfo1.EnumerateFiles("*", SearchOption.AllDirectories);
                foreach (FileInfo f in files) {
                    Console.WriteLine("\t{0}", f.FullName);
                }

dInfo1.Delete(true);

The Delete method through the following exception 

"The process cannot access the file 'test.txt' because it is being used by another process."

From my tests i notice that the Create method creates and locks the file. What can I do to release the file?

Thanks in advance

All replies (1)

Monday, June 27, 2016 6:04 AM âś…Answered

Ok solved

 string path = subdir1.FullName + @"\test.txt";
                FileInfo f1 = new FileInfo(path);
                FileStream ff = f1.Create();
                ff.Close();