3

Imagine a winform app, who copy updated assemblies from a source folder A to a destination folder B. I use simple DirectoryInfo.GetFiles methods to fill a listview, comparing version of assembly in folder A and B; if some assemblies are newer, I start my update method. In this method, before copying, I try if all file in B folder are not in use:

var B = new DirectoryInfo("myBfolder");
foreach (var file in aFolder.GetFiles())
{
    try
    {
        //File not in use
        File.Open(file.FullName, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
    }
    catch (Exception ex)
    {
        //File in use!
    }
}

Well, because of previous UpdateListView code, that use FileInfo to get info to show, all my files results in use!

FileInfo lock files! Is this possible?

Can someone suggest a way to bypass this problem?

Thank you, Nando

Ferdinando Santacroce
  • 1,047
  • 3
  • 12
  • 31

1 Answers1

6

no, it is File.Open who lock files.

try to put it into using:

using(var file = File.Open(file.FullName, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
   // process here
}
Andrey
  • 59,039
  • 12
  • 119
  • 163
  • 1
    I don't open any of theese files; I iterate files in folders, getting some infos like Name, Size, and Version. I use a method to get version if file is a .NET assembly: private Version GetVersion(string fullpath) { if (File.Exists(fullpath)) { try { Assembly ass = Assembly.LoadFrom(fullpath); if (ass != null) { return ass.GetName().Version; } } catch (Exception) { //Not an assembly file return new Version(0, 0, 0, 0); } } return new Version(0, 0, 0, 0); } Probably I found the guilty? – Ferdinando Santacroce Aug 26 '10 at 14:53
  • Mmm... Assembly is not a Disposable object; File.Exists() seems not to be a file locker, too. I'm confused: this simple work is becoming a big headache! – Ferdinando Santacroce Aug 26 '10 at 15:00
  • 1
    @Ferdinando Santacroce locker is `Assembly.LoadFrom` – Andrey Aug 26 '10 at 15:19
  • Commenting my GetVersion() method make thing run... Yes, is Assembly.LoadFrom! To get version of an assembly in non-locking mode what can I do? Copying file in a tmp folder and get version from these tmp files? Thank you! Nando – Ferdinando Santacroce Aug 26 '10 at 16:15
  • @Ferdinando Santacroce don't forget to accept the answer :) yes, you can avoid locking file by reading it to byte[] first as described here: http://stackoverflow.com/questions/1031431/system-reflection-assembly-loadfile-locks-file – Andrey Aug 26 '10 at 16:25
  • Thank you very much Andrey! :-) Bye, Nando – Ferdinando Santacroce Aug 27 '10 at 06:51