BITKit/Packages/Core/StorageProvider/LocalStorageProvider.cs

129 lines
3.8 KiB
C#

using Cysharp.Threading.Tasks;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BITKit.IO
{
[System.Serializable]
public class LocalStorageProvider : StorageProvider
{
protected virtual string GetAdress(string path)
{
return path;
}
public override async Task<string> Combine(string path1, string path2)
{
await UniTask.Yield();
return Path.Combine(GetAdress(path1), path2);
}
public override async Task<IStorageFile> CreateFile(string path)
{
await UniTask.Yield();
FileInfo fileInfo = new FileInfo(GetAdress(path));
FileProvider file = new(fileInfo);
return file;
}
public override void CreateFolder(string path)
{
DirectoryInfo directoryInfo = new DirectoryInfo(GetAdress(path));
directoryInfo.Create();
}
public override void DeleteFile(string path)
{
FileInfo file = new FileInfo(GetAdress(path));
file.Delete();
}
public override void DeleteFolder(string path)
{
DirectoryInfo directoryInfo = new DirectoryInfo(GetAdress(path));
directoryInfo.Delete();
}
public override async Task<bool> FileExists(string path)
{
await UniTask.Yield();
return File.Exists(GetAdress(path));
}
public override async Task<IStorageFile> GetFile(string path)
{
await UniTask.Yield();
return new FileProvider(new FileInfo(GetAdress(path)));
}
public override async Task<IEnumerable<IStorageFile>> ListFiles(string path)
{
await UniTask.Yield();
DirectoryInfo directoryInfo = new DirectoryInfo(GetAdress(path));
directoryInfo.Create();
return directoryInfo.GetFiles().Select(x => new FileProvider(x));
}
public override async Task<IEnumerable<IStorageFolder>> ListFolders(string path)
{
await UniTask.Yield();
DirectoryInfo directoryInfo = new DirectoryInfo(GetAdress(path));
return directoryInfo.GetDirectories().Select(x => new FolderProvider(x));
}
public override void RenameFile(string oldPath, string newPath)
{
File.Move(GetAdress(oldPath), GetAdress(newPath));
}
public override void RenameFolder(string oldPath, string newPath)
{
DirectoryInfo directoryInfo = new DirectoryInfo(GetAdress(oldPath));
directoryInfo.MoveTo(GetAdress(newPath));
}
public override void SaveStream(string path, Stream inputStream)
{
using (var fs = File.Create(GetAdress(path)))
{
inputStream.CopyTo(fs);
fs.Close();
fs.Dispose();
}
}
public override async Task<bool> TryCreateFolder(string path)
{
await UniTask.Yield();
DirectoryInfo dirInfo = new DirectoryInfo(GetAdress(path));
if (dirInfo.Exists is false)
{
dirInfo.Create();
return true;
}
else
{
return false;
}
}
public override async Task<bool> TrySaveStream(string path, Stream inputStream)
{
await UniTask.Yield();
try
{
SaveStream(path, inputStream);
return true;
}
catch (Exception ex)
{
BIT4Log.LogException(ex);
return false;
}
}
}
}