2021-11-12 乐帮网
c#
Save Stream As File In C#,从Stream二进制流中保存成文件,关键代码如下:
public static void SaveStreamAsFile(string filePath, Stream inputStream, string fileName) {
DirectoryInfo info = new DirectoryInfo(filePath);
if (!info.Exists) {
info.Create();
}
string path = Path.Combine(filePath, fileName);
using(FileStream outputFileStream = new FileStream(path, FileMode.Create)) {
inputStream.CopyTo(outputFileStream);
}
}
或者有这样的用法:
public void CopyStream(Stream stream, string destPath)
{
using (var fileStream = new FileStream(destPath, FileMode.Create, FileAccess.Write))
{
stream.CopyTo(fileStream);
}
}
也可以写成这样:
private void SaveFileStream(String path, Stream stream)
{
var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write);
stream.CopyTo(fileStream);
fileStream.Dispose();
}
想要更多控制可写成如下:
public void SaveStreamToFile(string fileFullPath, Stream stream)
{
if (stream.Length == 0) return;
// Create a FileStream object to write a stream to a file
using (FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length))
{
// Fill the bytes[] array with the stream data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, (int)bytesInStream.Length);
// Use FileStream object to write to the specified file
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
}
}
最后需要根据自己的实际业务逻辑进行调整。
https://www.c-sharpcorner.com/Blogs/save-stream-as-file-in-c-sharp
https://stackoverflow.com/questions/411592/how-do-i-save-a-stream-to-a-file-in-c
关注我的微信公众号
在公众号里留言交流
投稿邮箱:1052839972@qq.com
庭院深深深几许?杨柳堆烟,帘幕无重数。
玉勒雕鞍游冶处,楼高不见章台路。
雨横风狂三月暮。门掩黄昏,无计留春住。
泪眼问花花不语,乱红飞过秋千去。
如果感觉对您有帮助
欢迎向作者提供捐赠
这将是创作的最大动力