Utils/FileMutex.cs

72 lines
1.6 KiB
C#
Raw Permalink Normal View History

2017-03-09 20:58:12 +01:00
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace BlubbFish.Utils
{
public class FileMutex : IDisposable
{
2017-03-09 20:58:12 +01:00
private static FileMutex instance;
private String filename;
private StreamWriter file;
private FileMutex() { }
public static FileMutex Instance
{
2017-03-09 20:58:12 +01:00
get {
if (instance == null) {
instance = new FileMutex();
2017-03-09 20:58:12 +01:00
}
return instance;
2017-03-09 20:58:12 +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
}
public Boolean Create()
{
if (File.Exists(this.filename)) {
2017-03-09 20:58:12 +01:00
return false;
}
2017-03-09 20:58:12 +01:00
this.file = new StreamWriter(this.filename);
InitFile();
return File.Exists(this.filename) && this.file != null;
2017-03-09 20:58:12 +01:00
}
private void InitFile()
{
this.file.Write("Created: " + DateTime.Now.ToUniversalTime() + "\n");
2017-03-09 20:58:12 +01:00
this.file.Flush();
}
public Boolean Delete()
{
if(this.file != null) {
this.file.Close();
}
2017-03-09 20:58:12 +01:00
File.Delete(this.filename);
return !File.Exists(this.filename);
}
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
}
}