.NetCore跨平台保存文件
1.简介
在做.NetCore跨平台项目,会涉及到文件保存的操作。本文记录了该问题的解决方案。
2.操作
思路大致是文件流操作,采用MemoryStream将数据写到目的路径即可。
代码如下:
/// <summary>
/// 写文件到目的路径
/// </summary>
/// <param name="sourcePath">源文件的地址</param>
/// <param name="destinationPath">目的地址</param>
/// <returns></returns>
public static async Task SaveFile(string sourcePath, string destinationPath)
{
if (string.IsNullOrEmpty(destinationPath) || string.IsNullOrEmpty(sourcePath)) //表示没有选中目的存放地址 源地址
{
return;
}
if (IsDirectory(sourcePath)) throw new InvalidOperationException("Can't download directory.");
using (MemoryStream stmMemory = new MemoryStream())
{
using (Stream stream = File.OpenRead(sourcePath))
{
byte[] buffer = new byte[stream.Length];
int i;
//将字节逐个放入到Byte中
while ((i = stream.Read(buffer, 0, buffer.Length)) > 0)
{
stmMemory.Write(buffer, 0, i);
}
byte[] fileBytes;
fileBytes = stmMemory.ToArray();//文件流Byte
using (FileStream fs = new FileStream(destinationPath, FileMode.OpenOrCreate))
{
stmMemory.WriteTo(fs);
}
}
}
}
3.总结
小技巧,积累即可,方便自己,方便大家。