可能重复:
如何将流保存到文件?
我有一个流对象,可能是一个图像或文件(msword,pdf),我决定以非常不同的方式处理这两种类型,因为我可能想要优化/压缩/调整大小/生成缩略图等.我调用一个特定的方法来将图像保存到磁盘,代码:
var file = StreamObject;
//if content-type == jpeg, png, bmp do...
Image _image = Image.FromStream(file);
_image.Save(path);
//if pdf, word do...
Run Code Online (Sandbox Code Playgroud)
我如何实际保存单词和PDF?
//multimedia/ video?
Run Code Online (Sandbox Code Playgroud)
我看了(可能不够硬)但我找不到任何地方......
rot*_*man 26
如果您使用的是.NET 4.0或更高版本,则可以使用此方法:
public static void CopyStream(Stream input, Stream output)
{
input.CopyTo(output);
}
Run Code Online (Sandbox Code Playgroud)
如果没有,请使用以下一个:
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ( (len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
Run Code Online (Sandbox Code Playgroud)
在这里如何使用它:
using (FileStream output = File.OpenWrite(path))
{
CopyStream(input, output);
}
Run Code Online (Sandbox Code Playgroud)
She*_*Pro 19
对于文件类型,您可以依赖FileExtentions并将其写入磁盘,您可以使用BinaryWriter.或FileStream.
示例(假设您已有流):
FileStream fileStream = File.Create(fileFullPath, (int)stream.Length);
// Initialize the bytes array with the stream length and then fill it with data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, bytesInStream.Length);
// Use write method to write to the file specified above
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
//Close the filestream
fileStream.Close();
Run Code Online (Sandbox Code Playgroud)