How do I save a stream to a file in C#?(如何在 C# 中将流保存到文件中?)
问题描述
我有一个用流初始化的 StreamReader 对象,现在我想将此流保存到磁盘(流可能是 .gif 或 .jpg 或 .pdf).
I have a StreamReader object that I initialized with a stream, now I want to save this stream to disk (the stream may be a .gif or .jpg or .pdf).
现有代码:
StreamReader sr = new StreamReader(myOtherObject.InputStream);
- 我需要将它保存到磁盘(我有文件名).
- 将来我可能希望将其存储到 SQL Server.
我也有编码类型,如果我将它存储到 SQL Server,我将需要它,对吗?
I have the encoding type also, which I will need if I store it to SQL Server, correct?
推荐答案
正如 Tilendor 在 Jon Skeet 的回答中强调的那样,从 .NET 4 开始,流就有一个 CopyTo 方法.
As highlighted by Tilendor in Jon Skeet's answer, streams have a CopyTo method since .NET 4.
var fileStream = File.Create("C:\Path\To\File");
myOtherObject.InputStream.Seek(0, SeekOrigin.Begin);
myOtherObject.InputStream.CopyTo(fileStream);
fileStream.Close();
或者使用 using 语法:
using (var fileStream = File.Create("C:\Path\To\File"))
{
myOtherObject.InputStream.Seek(0, SeekOrigin.Begin);
myOtherObject.InputStream.CopyTo(fileStream);
}
这篇关于如何在 C# 中将流保存到文件中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在 C# 中将流保存到文件中?
基础教程推荐
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
