55 lines
2.0 KiB
C#
55 lines
2.0 KiB
C#
using System.IO;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Knoks.Framework.Extentions
|
|
{
|
|
public static class FileInfoExtentions
|
|
{
|
|
public static async Task<bool> ArchiveFile(this FileInfo fileInfo)
|
|
{
|
|
var archiveFullName = GenerateArchiveFullName(fileInfo);
|
|
if (archiveFullName == fileInfo.FullName)
|
|
return false;
|
|
|
|
using (var src = fileInfo.OpenRead())
|
|
using (var dst = new FileStream(archiveFullName, FileMode.CreateNew))
|
|
{
|
|
await src.CopyToAsync(dst);
|
|
return true;
|
|
}
|
|
}
|
|
|
|
public static string GenerateArchiveFullName(this FileInfo fileInfo)
|
|
{
|
|
string archiveFullName = fileInfo.FullName;
|
|
|
|
string fileNameOnly = Path.GetFileNameWithoutExtension(fileInfo.FullName);
|
|
string extension = Path.GetExtension(fileInfo.FullName);
|
|
string path = Path.GetDirectoryName(fileInfo.FullName);
|
|
|
|
int count = 1;
|
|
while (System.IO.File.Exists(archiveFullName))
|
|
{
|
|
string tempFileName = string.Format("{0}-({1})", fileNameOnly, count++);
|
|
archiveFullName = Path.Combine(path, tempFileName + extension);
|
|
}
|
|
|
|
return archiveFullName;
|
|
}
|
|
|
|
public static DirectoryInfo CreateDirectory(this FileInfo fileInfo)
|
|
{
|
|
return Directory.Exists(fileInfo.DirectoryName) ?
|
|
new DirectoryInfo(fileInfo.DirectoryName) :
|
|
Directory.CreateDirectory(fileInfo.DirectoryName);
|
|
}
|
|
public static Stream ParseImage(string data)
|
|
{
|
|
var base64Data = System.Text.RegularExpressions.Regex.Match(data, @"data:image/(?<type>.+?),(?<data>.+)").Groups["data"].Value;
|
|
byte[] imageBytes = System.Convert.FromBase64String(base64Data);
|
|
MemoryStream ms = new MemoryStream(imageBytes, writable: false);
|
|
return ms;
|
|
}
|
|
}
|
|
}
|