Home » Questions » Computers [ Ask a new question ]

Need some efficient method to Lock/Unlock files

Need some efficient method to Lock/Unlock files

I'm developing a small tool and I need to test it again system-level locked files. I'm in search of some small application (or some easy method my tired brain is not coming up with) that allows me to lock and unlock files at will. Something like Unlocker but that allows me also to lock.

Asked by: Guest | Views: 74
Total answers/comments: 1
Guest [Entry]

"More StackOverflow geared, but I can't believe something this simple doesn't exist already. Here's the C# code (feel free to modify it, hacked it together quick):

using System;
using System.IO;
using System.Text;
using System.Threading;

class LockFile
{
public static void Main(String[] args)
{
if (args.Length > 2)
{
Console.WriteLine(""Usage: lockfile <file> <wait_in_ms>"");
Environment.Exit(0);
}
string path = args[0];
try
{
File.Open(path, FileMode.Open, FileAccess.Write, FileShare.None);
Thread.Sleep(int.Parse(args[1]));
}
catch (FileNotFoundException e)
{
Console.WriteLine(""File not found, exiting."");
Environment.Exit(0);
}
}
}

Usage:

lockfile c:\somefile.txt 30000

locks the file specified for 30 seconds. When trying to access it you will a message like this:

Here's a compiled binary, .NET framework required. I'll recode it in another language if you need a native binary, just ask in the comments :)"