ln.types/odb/ng/storage/FSStorageContainer.cs

98 lines
2.6 KiB
C#

// /**
// * File: FSStorage.cs
// * Author: haraldwolff
// *
// * This file and it's content is copyrighted by the Author and / or copyright holder.
// * Any use wihtout proper permission is illegal and may lead to legal actions.
// *
// *
// **/
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ln.types.odb.ng.storage
{
public class FSStorageContainer : IStorageContainer,IDisposable
{
public string BasePath { get; }
FileStream lockFile;
Dictionary<string, FSStorage> storages = new Dictionary<string, FSStorage>();
public FSStorageContainer(string basePath)
{
BasePath = basePath;
}
public bool IsOpen => lockFile != null;
private void AssertOpen()
{
if (!IsOpen)
throw new IOException("FSSTorage not open");
}
public void Close()
{
lock (this)
{
AssertOpen();
if (lockFile != null)
{
lockFile.Close();
lockFile.Dispose();
lockFile = null;
}
}
}
public IStorage GetStorage(string storageName)
{
lock (this)
{
AssertOpen();
if (!storages.ContainsKey(storageName))
storages.Add(storageName, new FSStorage(Path.Combine(BasePath, storageName)));
return storages[storageName];
}
}
public IEnumerable<string> GetStorageNames()
{
lock (this)
{
AssertOpen();
return storages.Keys;
}
}
public void Open()
{
lock (this)
{
if (!IsOpen)
{
if (!Directory.Exists(BasePath))
Directory.CreateDirectory(BasePath);
lockFile = new FileStream(Path.Combine(BasePath, ".lock"), FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None, 1024, FileOptions.DeleteOnClose);
foreach (String storagePath in Directory.EnumerateDirectories(BasePath))
{
FSStorage storage = new FSStorage(storagePath);
storages.Add(storage.StorageName, storage);
}
}
}
}
public void Dispose()
{
if (IsOpen)
Close();
}
}
}