weismat
weismat

Reputation: 7411

C# accessing locked files

I want to access a file via c# which is created and still processed via a different program.
Currently I am copying the file via the Windows explorer to a different location and work then with the copy. As the copy is large I would prefer to work straight with the original file. Is there any way?
The normal FileStream does not allow any shared access mode. I have control over both programs, so I could change the writer as well if neccessary.

Upvotes: 4

Views: 2339

Answers (2)

Tomasz Żmuda
Tomasz Żmuda

Reputation: 637

You can use my library for accessing files from multiple apps.

You can install it from nuget: Install-Package Xabe.FileLock

If you want more information about it check https://github.com/tomaszzmuda/Xabe.FileLock

ILock fileLock = new FileLock(file);
if(fileLock.Acquire(TimeSpan.FromSeconds(15), true))
{
    using(fileLock)
    {
        // file operations here
    }
}

fileLock.Acquire method will return true only if can lock file exclusive for this object. But app which uploading file must do it in file lock too. If object is inaccessible metod returns false.

So if you want use it, you have to install this package of both app and lock file before change data in it and then immediately release lock.

Upvotes: 0

SoftArtisans
SoftArtisans

Reputation: 536

You will need to make sure that the program doing the writing and reading have the right FileShare set, so you'll need to pass FileShare.Read into the FileStream constructor for the program writing:

new FileStream("C:/Users/phil/tmp.txt",FileMode.Create,FileAccess.Write,FileShare.Read)

You will also want to make sure that you have FileShare.ReadWrite enabled for the program that's just reading it in:

new FileStream("C:/Users/phil/tmp.txt",FileMode.Open,FileAccess.Read,FileShare.ReadWrite)

This will cause the FileStream constructors to put the correct locks on the file itself.

You can find out more about the constructor on msdn: http://msdn.microsoft.com/en-us/library/5h0z48dh.aspx (there are also other overloads that also take a FileShare parameter)

Upvotes: 4

Related Questions