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

79 lines
1.9 KiB
C#
Raw Normal View History

2025-01-05 17:05:23 +03:00
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;
}
public bool TryOpen(string path, out Stream? stream)
{
2025-01-08 18:00:06 +03:00
var fullPath = Path.Join(RootPath, path);
if (File.Exists(fullPath))
2024-12-22 16:38:47 +03:00
{
2025-01-08 18:00:06 +03:00
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
}
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
}
public IEnumerable<string> AllFiles => Directory.EnumerateFiles(RootPath, "*.*", SearchOption.AllDirectories);
}