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