Files
NebulaLauncher/Nebula.Shared/FileApis/FileApi.cs

85 lines
2.1 KiB
C#
Raw Normal View History

2025-01-19 22:52:29 +03:00
using System.Diagnostics.CodeAnalysis;
using Nebula.Shared.FileApis.Interfaces;
2024-12-22 16:38:47 +03:00
2025-01-05 17:05:23 +03:00
namespace Nebula.Shared.FileApis;
2024-12-22 16:38:47 +03:00
2025-01-08 18:00:06 +03:00
public sealed class FileApi : IReadWriteFileApi
2024-12-22 16:38:47 +03:00
{
public string RootPath;
public FileApi(string rootPath)
{
RootPath = rootPath;
}
2025-01-19 22:52:29 +03:00
public bool TryOpen(string path,[NotNullWhen(true)] out Stream? stream)
2024-12-22 16:38:47 +03:00
{
2025-01-08 18:00:06 +03:00
var fullPath = Path.Join(RootPath, path);
if (File.Exists(fullPath))
try
{
stream = new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
return true;
}
catch
{
stream = null;
return false;
}
2024-12-22 16:38:47 +03:00
stream = null;
return false;
}
public bool Save(string path, Stream input)
{
var currPath = Path.Join(RootPath, path);
2025-01-08 18:00:06 +03:00
try
{
var dirInfo = new DirectoryInfo(Path.GetDirectoryName(currPath) ?? throw new InvalidOperationException());
if (!dirInfo.Exists) dirInfo.Create();
2024-12-22 16:38:47 +03:00
2025-01-08 18:00:06 +03:00
using var stream = new FileStream(currPath, FileMode.Create, FileAccess.Write, FileShare.None);
input.CopyTo(stream);
return true;
}
catch
{
return false;
}
2024-12-22 16:38:47 +03:00
}
public bool Remove(string path)
{
2025-01-08 18:00:06 +03:00
var fullPath = Path.Join(RootPath, path);
try
{
if (File.Exists(fullPath))
{
File.Delete(fullPath);
return true;
}
}
catch
{
// Log exception if necessary
}
2025-01-14 22:10:16 +03:00
2025-01-08 18:00:06 +03:00
return false;
2024-12-22 16:38:47 +03:00
}
public bool Has(string path)
{
2025-01-08 18:00:06 +03:00
var fullPath = Path.Join(RootPath, path);
return File.Exists(fullPath);
2024-12-22 16:38:47 +03:00
}
2025-03-15 22:16:00 +03:00
private IEnumerable<string> GetAllFiles(){
if(!Directory.Exists(RootPath)) return [];
return Directory.EnumerateFiles(RootPath, "*.*", SearchOption.AllDirectories).Select(p=>p.Replace(RootPath,"").Substring(1));
}
public IEnumerable<string> AllFiles => GetAllFiles();
2024-12-22 16:38:47 +03:00
}