The most solid and bulletproof solution is Mutex — it's a kernel-level Windows synchronization primitive:
bool acquired = false;
using(var mutex = new Mutex(false, "MyFolderMutex"))
{
try
{
acquired = mutex.WaitOne();
// Your file/folder operations here
}
finally
{
if (acquired)
mutex.ReleaseMutex();
}
}
Why Mutex is the most reliable:
- OS-level guarantee — Windows kernel handles the synchronization
- Cross-process — works even between different ZennoPoster instances or external apps
- Crash-safe — if your thread crashes, OS automatically releases the mutex
- Named — any process in the system can see "MyFolderMutex" and wait for it
Tip: Make your mutex name unique to the folder, e.g.:
string mutexName = "FolderLock_" + folderPath.GetHashCode();
This is the "nuclear option" — slower than lock() but guaranteed to work in any scenario.