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:
parent
60dbb5b92d
commit
a05841d75c
BackupEssentials
@ -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" />
|
||||
|
35
BackupEssentials/Utils/FileLock.cs
Normal file
35
BackupEssentials/Utils/FileLock.cs
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user