A.Pissicat
A.Pissicat

Reputation: 3295

Lock file for application

I working on a service. This service will run on 2 gears using a shared folder.

Shared folder contains images, the service read an image, do some stuff and move the file. I want that the both running services can't access to the same file and prevent user from deleting processing file.

Actually I have this :

DirectoryInfo info = new DirectoryInfo("My Folder");
List<FileInfo> fileList = info.GetFiles();
foreach (FileInfo file in fileList)
{
    bool createdNew;
    Mutex fileLocker = new Mutex(true, file.Name, out createdNew);
    if (createdNew)
    {
        BitmapImage bitmapImage = new BitmapImage(new Uri(file.FullName));
       // Do some stuff
       if (null != fileLocker) fileLocker.ReleaseMutex();
    }
}

It prevent 2 access the file on the same machine but not in separate, and user can delete file while the service is using it.

How can I lock the file properly ?

Upvotes: 2

Views: 352

Answers (1)

V0ldek
V0ldek

Reputation: 10613

Open your file using a FileStream and specify the FileShare parameter:

var file = new FileStream(name, FileMode.Create, FileAccess.ReadWrite, FileShare.None);

EDIT:

To use BitmapImage with a FileStream you need to use the BitmapImage.StreamSource property. So something like this:

var bitmapImage = new BitmapImage();

var file = new FileStream(name, FileMode.Create, FileAccess.ReadWrite, FileShare.None)
bitmapImage.BeginInit();
bitmapImage.StreamSource = file;
bitmapImage.EndInit();

After this you need to decide how you're gonna handle the Stream's disposal. You can either force the bitmap to cache it and then clean it up immediately, or let the bitmap retain stream access. More on this here.

Upvotes: 4

Related Questions