- tweak: file managment

This commit is contained in:
2025-01-08 18:00:06 +03:00
parent b16b21e954
commit e5ed27f72d
20 changed files with 539 additions and 161 deletions

View File

@@ -2,7 +2,7 @@
namespace Nebula.Shared.FileApis;
public class FileApi : IReadWriteFileApi
public sealed class FileApi : IReadWriteFileApi
{
public string RootPath;
@@ -13,10 +13,19 @@ public class FileApi : IReadWriteFileApi
public bool TryOpen(string path, out Stream? stream)
{
if (File.Exists(Path.Join(RootPath, path)))
var fullPath = Path.Join(RootPath, path);
if (File.Exists(fullPath))
{
stream = File.OpenRead(Path.Join(RootPath, path));
return true;
try
{
stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
return true;
}
catch
{
stream = null;
return false;
}
}
stream = null;
@@ -27,27 +36,43 @@ public class FileApi : IReadWriteFileApi
{
var currPath = Path.Join(RootPath, path);
var dirInfo = new DirectoryInfo(Path.GetDirectoryName(currPath));
if (!dirInfo.Exists) dirInfo.Create();
try
{
var dirInfo = new DirectoryInfo(Path.GetDirectoryName(currPath) ?? throw new InvalidOperationException());
if (!dirInfo.Exists) dirInfo.Create();
using var stream = File.OpenWrite(currPath);
input.CopyTo(stream);
stream.Flush();
stream.Close();
return true;
using var stream = new FileStream(currPath, FileMode.Create, FileAccess.Write, FileShare.None);
input.CopyTo(stream);
return true;
}
catch
{
return false;
}
}
public bool Remove(string path)
{
if (!Has(path)) return false;
File.Delete(Path.Join(RootPath, path));
return true;
var fullPath = Path.Join(RootPath, path);
try
{
if (File.Exists(fullPath))
{
File.Delete(fullPath);
return true;
}
}
catch
{
// Log exception if necessary
}
return false;
}
public bool Has(string path)
{
var currPath = Path.Join(RootPath, path);
return File.Exists(currPath);
var fullPath = Path.Join(RootPath, path);
return File.Exists(fullPath);
}
public IEnumerable<string> AllFiles => Directory.EnumerateFiles(RootPath, "*.*", SearchOption.AllDirectories);