.net 如何将 System.IO.Stream 转换为字符串,然后再转换回 System.IO.Stream
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4316363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to convert System.IO.Stream into string and then back to System.IO.Stream
提问by SOF User
I have property of Streamtype
我有Stream类型的财产
public System.IO.Stream UploadStream { get; set; }
How can I convert it into a stringand send on to other side where I can again convert it into System.IO.Stream?
如何将其转换为 astring并将其发送到另一侧,我可以再次将其转换为System.IO.Stream?
回答by Darin Dimitrov
I don't know what do you mean by converting a stream to a string. Also what's the other side?
我不知道将流转换为字符串是什么意思。还有另一面是什么?
In order to convert a stream to a string you need to use an encoding. Here's an example of how this could be done if we suppose that the stream represents UTF-8 encoded bytes:
为了将流转换为字符串,您需要使用编码。如果我们假设流表示 UTF-8 编码的字节,这是一个如何完成的示例:
using (var reader = new StreamReader(foo.UploadStream, Encoding.UTF8))
{
string value = reader.ReadToEnd();
// Do something with the value
}
回答by LostNomad311
After some searching , other answers to this question suggest you can do this without knowing / using the string's encoding . Since a stream is just bytes , those solutions are limited at best . This solution considers the encoding:
经过一番搜索,此问题的其他答案表明您可以在不知道/使用字符串的 encoding 的情况下执行此操作。由于流只是字节,因此这些解决方案充其量是有限的。此解决方案考虑了编码:
public static String ToEncodedString(this Stream stream, Encoding enc = null)
{
enc = enc ?? Encoding.UTF8;
byte[] bytes = new byte[stream.Length];
stream.Position = 0;
stream.Read(bytes, 0, (int)stream.Length);
string data = enc.GetString(bytes);
return enc.GetString(bytes);
}
source - http://www.dotnetfunda.com/codes/show/130/how-to-convert-stream-into-string
来源 - http://www.dotnetfunda.com/codes/show/130/how-to-convert-stream-into-string
String to Stream - https://stackoverflow.com/a/35173245/183174

