gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:49:25 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com