Files
irc-netcore-api/IRaCIS.Core.Infrastructure/Extention/FileExt.cs
T
2022-03-28 15:27:40 +08:00

63 lines
2.2 KiB
C#

using System.IO;
using System.Threading.Tasks;
namespace IRaCIS.Core.Infrastructure.Extention
{
/// <summary>
/// 大文件操作扩展类
/// </summary>
public static class FileExt
{
/// <summary>
/// 以文件流的形式复制大文件
/// </summary>
/// <param name="fs">源</param>
/// <param name="dest">目标地址</param>
/// <param name="bufferSize">缓冲区大小,默认8MB</param>
public static void CopyToFile(this Stream fs, string dest, int bufferSize = 1024 * 8 * 1024)
{
using var fsWrite = new FileStream(dest, FileMode.OpenOrCreate, FileAccess.ReadWrite);
byte[] buf = new byte[bufferSize];
int len;
while ((len = fs.Read(buf, 0, buf.Length)) != 0)
{
fsWrite.Write(buf, 0, len);
}
}
/// <summary>
/// 以文件流的形式复制大文件(异步方式)
/// </summary>
/// <param name="fs">源</param>
/// <param name="dest">目标地址</param>
/// <param name="bufferSize">缓冲区大小,默认8MB</param>
public static async void CopyToFileAsync(this Stream fs, string dest, int bufferSize = 1024 * 1024 * 8)
{
using var fsWrite = new FileStream(dest, FileMode.OpenOrCreate, FileAccess.ReadWrite);
byte[] buf = new byte[bufferSize];
int len;
await Task.Run(() =>
{
while ((len = fs.Read(buf, 0, buf.Length)) != 0)
{
fsWrite.Write(buf, 0, len);
}
}).ConfigureAwait(true);
}
/// <summary>
/// 将内存流转储成文件
/// </summary>
/// <param name="ms"></param>
/// <param name="filename"></param>
public static void SaveFile(this MemoryStream ms, string filename)
{
using var fs = new FileStream(filename, FileMode.Create, FileAccess.Write);
byte[] buffer = ms.ToArray(); // 转化为byte格式存储
fs.Write(buffer, 0, buffer.Length);
fs.Flush();
}
}
}