Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Blocking a folder from being changed while processing

Tags:

c#

.net

I have a single-threaded program that processes folders and files in a source directory. Is there a way to block a folder, with files in it, within my source directory from being modified by other processes while my program is working on it? I'm thinking something along the lines of placing some kind of exclusive lock on the folder itself, so only my program's process can use it.

NOTE:

I do not want to block the root source directory itself, just whatever folder(s), in the top level of that directory, I might be processing at any particular moment. I still want to be able to allow outside processes to add folders to the source directory, while I'm processing other folders.

UPDATE:

@Yuri - Yes this is a Windows program, a Windows Service application to be exact.

Part of what makes this both challenging and necessary is that I need to recreate the structure of whatever folder(s) I'm processing, in the source directory, in a separate destination directory. So I can't have a any other process modifying the folder(s) and File(s) while my program is working with them.

like image 903
kingrichard2005 Avatar asked Jan 14 '11 15:01

kingrichard2005


2 Answers

Ways to lock a folder:

1.Mark it readonly. (Included because people always try this)
Con - This does not actually work. On folders, the readonly flag is used for other purposes.

2.Mark all of the contents readonly.
Con - Won't prevent certain types of actions (e.g., creating new items).

3.Use ACL
Con - Won't prevent administrators from messing with the folder. Requires certain types of permissions.

4.Use ACL with a specially created user and enable folder Encryption.
Con - This is really of horrifying. If anything goes wrong, your data might be lost.

5.Rename/Move the folder
Con - Can be bypassed by user stupidity.

6.(Edit) gjvdkamp's answer: Lock Individual files
Con - As with #2, this still allows creating new files within the folders. That said, this is The Right Way™ to do it.

like image 143
Brian Avatar answered Oct 14 '22 15:10

Brian


edit don't us this hack, doesn't work: http://itknowledgeexchange.techtarget.com/itanswers/folder-lock/

Else i would loop over all files in foder, create a list<FileStream> and then call Lock on each. This would give you finer grained control over wich files to lock.

GJ

Edit: Try something along these lines:

var locks = new List<FileStream>();
var di = new DirectoryInfo(@"C:\Test");
foreach (var file in di.GetFiles()) {
    var fs = new FileStream(file.FullName, FileMode.Open);
    fs.Lock(0, 0);
    locks.Add(fs);
}
like image 25
gjvdkamp Avatar answered Oct 14 '22 15:10

gjvdkamp