1
0
mirror of https://github.com/chylex/Backup-Essentials.git synced 2025-05-31 09:34:07 +02:00

Added FileLock

This commit is contained in:
chylex 2015-05-16 16:49:42 +02:00
parent 60dbb5b92d
commit a05841d75c
2 changed files with 36 additions and 0 deletions

View File

@ -140,6 +140,7 @@
<DependentUpon>TestingWindow.xaml</DependentUpon>
</Compile>
<Compile Include="Sys\UI\DateFormat.cs" />
<Compile Include="Utils\FileLock.cs" />
<Compile Include="Utils\FileUtils.cs" />
<Compile Include="Utils\KeyEqualityComparer.cs" />
<Compile Include="Utils\NativeMethods.cs" />

View File

@ -0,0 +1,35 @@
using System.Diagnostics;
using System.IO;
namespace BackupEssentials.Utils{
class FileLock{
private static readonly int processID = Process.GetCurrentProcess().Id;
private readonly string FileName;
private bool IsLocked;
public FileLock(string lockFileName){
this.FileName = lockFileName;
}
public bool TryLock(){
if (FileUtils.WriteFile(FileName,FileMode.CreateNew,(writer) => { writer.Write(processID); })){
IsLocked = false;
FileUtils.ReadFile(FileName,FileMode.Open,(line) => { IsLocked = line.Equals(processID.ToString()); });
return IsLocked;
}
else return false;
}
public bool ReleaseLock(){
if (IsLocked){
try{
File.Delete(FileName);
return true;
}catch(IOException){}
}
return false;
}
}
}