views:

34

answers:

1

Hi all.

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

+2  A: 

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
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
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
@Ferdinando Santacroce locker is `Assembly.LoadFrom`
Andrey
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
@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
Thank you very much Andrey! :-)Bye, Nando
Ferdinando Santacroce