c# - 如何在不转到磁盘的情况下将字符串加载到 FileStream 中?

标签 c# filestream

string abc = "This is a string";

如何将 abc 加载到 FileStream 中?

FileStream input = new FileStream(.....);

最佳答案

使用 MemoryStream相反……

MemoryStream ms = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(abc));

请记住,MemoryStream(就像 FileStream 一样)在您使用完后需要关闭。您始终可以将您的代码放在 using block 中以简化此操作...

using(MemoryStream ms = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(abc)))
{
   //use the stream here and don't worry about needing to close it
}

注意:如果您的字符串是 Unicode 而不是 ASCII,您可能希望在转换为字节数组时指定它。基本上,一个 Unicode 字符占用 2 个字节而不是 1 个字节。如果需要,将添加填充(例如 0x00 0x61 = "a"in unicode,而在 ASCII 中 0x61 = “一个”)

关于c# - 如何在不转到磁盘的情况下将字符串加载到 FileStream 中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8897962/

相关文章:

c# - 无法从 C# 调用用 C++ 编写的 dll 函数

c# - 在 VSTS 上运行 asp.net 核心 sln 我得到了 : Error MSB4018: The "TransformWebConfig" task failed unexpectedly

C# 从文件序列化数据契约(Contract)

.net - 何时使用 Using 语句

c# - 将类视为使用接口(interface)定义的类

c# - ASP.NET Core 2.0 应用程序超时时重定向到绝对 URL

c# - MenuItem 事件未在 asp.net 菜单中触发

node.js - 将 Pdf 缓冲区转换为 jpg 图像缓冲区 ( NodeJS )

c# - File.OpenWrite 给出错误,而 FileStream(sFile, FileMode.Open, FileAccess.ReadWrite) 没有

node.js - 在 Node.js 中处理 100MB 文件