2017-03-09 20:58:12 +01:00
|
|
|
|
using System;
|
|
|
|
|
using System.IO;
|
|
|
|
|
using System.Security.Cryptography;
|
|
|
|
|
using System.Text;
|
|
|
|
|
|
2017-03-09 23:32:42 +01:00
|
|
|
|
namespace BlubbFish.Utils
|
|
|
|
|
{
|
2017-04-21 23:55:26 +02:00
|
|
|
|
public class FileMutex : IDisposable
|
2017-03-09 23:32:42 +01:00
|
|
|
|
{
|
2017-03-09 20:58:12 +01:00
|
|
|
|
private static FileMutex instance;
|
|
|
|
|
private String filename;
|
|
|
|
|
private StreamWriter file;
|
|
|
|
|
private FileMutex() { }
|
|
|
|
|
|
2017-03-09 23:32:42 +01:00
|
|
|
|
public static FileMutex Instance
|
|
|
|
|
{
|
2017-03-09 20:58:12 +01:00
|
|
|
|
get {
|
2017-03-09 23:32:42 +01:00
|
|
|
|
if (instance == null) {
|
|
|
|
|
instance = new FileMutex();
|
2017-03-09 20:58:12 +01:00
|
|
|
|
}
|
2017-03-09 23:32:42 +01:00
|
|
|
|
return instance;
|
2017-03-09 20:58:12 +01:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2017-03-09 23:32:42 +01:00
|
|
|
|
public void SetName(String name)
|
|
|
|
|
{
|
|
|
|
|
String path = AppDomain.CurrentDomain.BaseDirectory;
|
|
|
|
|
this.filename = path + String.Join(String.Empty, Array.ConvertAll(new SHA512Managed().ComputeHash(Encoding.UTF8.GetBytes(name)), b => b.ToString("X2"))) + ".lock.txt";
|
2017-03-09 20:58:12 +01:00
|
|
|
|
}
|
|
|
|
|
|
2017-03-09 23:32:42 +01:00
|
|
|
|
public Boolean Create()
|
|
|
|
|
{
|
|
|
|
|
if (File.Exists(this.filename)) {
|
2017-03-09 20:58:12 +01:00
|
|
|
|
return false;
|
2017-03-09 23:32:42 +01:00
|
|
|
|
}
|
|
|
|
|
|
2017-03-09 20:58:12 +01:00
|
|
|
|
this.file = new StreamWriter(this.filename);
|
2017-03-09 23:32:42 +01:00
|
|
|
|
InitFile();
|
|
|
|
|
return File.Exists(this.filename) && this.file != null;
|
2017-03-09 20:58:12 +01:00
|
|
|
|
}
|
|
|
|
|
|
2017-03-09 23:32:42 +01:00
|
|
|
|
private void InitFile()
|
|
|
|
|
{
|
|
|
|
|
this.file.Write("Created: " + DateTime.Now.ToUniversalTime() + "\n");
|
2017-03-09 20:58:12 +01:00
|
|
|
|
this.file.Flush();
|
|
|
|
|
}
|
|
|
|
|
|
2017-03-09 23:32:42 +01:00
|
|
|
|
public Boolean Delete()
|
|
|
|
|
{
|
2017-04-18 14:27:11 +02:00
|
|
|
|
if(this.file != null) {
|
|
|
|
|
this.file.Close();
|
|
|
|
|
}
|
|
|
|
|
|
2017-03-09 20:58:12 +01:00
|
|
|
|
File.Delete(this.filename);
|
|
|
|
|
return !File.Exists(this.filename);
|
|
|
|
|
}
|
2017-04-21 23:55:26 +02:00
|
|
|
|
|
|
|
|
|
protected virtual void Dispose(Boolean disposing) {
|
|
|
|
|
if (disposing) {
|
|
|
|
|
if(this.file != null) {
|
|
|
|
|
this.file.Close();
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
public void Dispose() {
|
|
|
|
|
Dispose(true);
|
|
|
|
|
GC.SuppressFinalize(this);
|
|
|
|
|
}
|
2017-03-09 20:58:12 +01:00
|
|
|
|
}
|
|
|
|
|
}
|