使用c#将文件(从流)保存到磁盘

Har*_*oon 18 .net c#

可能重复:
如何将流保存到文件?

我有一个流对象,可能是一个图像或文件(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)

  • 由于以上代码是从[本SO答案](http://stackoverflow.com/a/411605/678801)复制而来的,我相信回复原始答案的参考资料已经到位. (4认同)
  • 你确定吗?也许来自[这一个](http://stackoverflow.com/questions/230128/best-way-to-copy-between-two-stream-instances)?或者也许来自[Spring.NET源代码](https://github.com/spring-projects/spring-net/blob/master/src/Spring/Spring.Core/Util/IoUtils.cs)?我想这个实现更老了.也许我现在使用了Jon的答案中的代码,但是我记不起来了,因为差不多是4年前;) (4认同)

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)

  • 我把它作为***危险代码***投票.`Stream.Read`不保证它将满足指定长度的读取(`bytesInStream.Length`).这就是它返回一个表示实际读取量的值的原因.通过忽略此返回值并且在"amtReturned <bytesInStream.Length"的情况下无法正常操作,此代码是一种危险的维护危险,有时可能会起作用(对于短流),但**会在您的脸上更快地爆炸或以后.**不要使用此代码**. (9认同)
  • 谢谢,我把文件流包装在一个using语句中...... (2认同)