.net 将字符串转换为流
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/351126/
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
Convert a String to Stream
提问by InfoStatus
I've download an image from the Internet and converted to a String (This is not changeable)
我从网上下载了一张图片并转换为字符串(这是不可更改的)
Dim Request As System.Net.WebRequest = _
System.Net.WebRequest.Create( _
"http://www.google.com/images/nav_logo.png")
Dim WebResponse As System.Net.HttpWebResponse = _
DirectCast(Request.GetResponse(), System.Net.HttpWebResponse)
Dim Stream As New System.IO.StreamReader( _
WebResponse.GetResponseStream, System.Text.Encoding.UTF8)
Dim Text as String = Stream.ReadToEnd
How can I convert the String back to the Stream?
如何将字符串转换回流?
So I can use that stream to get the image.
所以我可以使用该流来获取图像。
Like this:
像这样:
Dim Image As New Drawing.Bitmap(WebResponse.GetResponseStream)
But now I've only the Text String, so I need something like this:
但现在我只有文本字符串,所以我需要这样的东西:
Dim Stream as Stream = ReadToStream(Text, System.Text.Encoding.UTF8)
Dim Image As New Drawing.Bitmap(Stream)
EDIT:
编辑:
This engine was primarily used for downloading web pages but I'm trying to use it for downloading images too. The format of the string is UTF8, as given in the example code...
该引擎主要用于下载网页,但我也尝试将其用于下载图像。字符串的格式为 UTF8,如示例代码中所示...
I've tried to use the MemoryStream(Encoding.UTF8.GetBytes(Text)), but I got this error when loading the stream to the image:
我尝试使用MemoryStream(Encoding.UTF8.GetBytes(Text)),但是在将流加载到图像时出现此错误:
A generic error occurred in GDI+.
GDI+ 中出现一般错误。
What gets lost in the conversions?
在转换中丢失了什么?
回答by Marc Gravell
Why have you converted binary (image) data to a string? This makes no sense... unless you are using base-64?
为什么要将二进制(图像)数据转换为字符串?这毫无意义……除非您使用 base-64?
Anyway, to reverse what you have done, you could try using new MemoryStream(Encoding.UTF8.GetBytes(text))?
无论如何,要扭转您所做的事情,您可以尝试使用new MemoryStream(Encoding.UTF8.GetBytes(text))?
This will create a new MemoryStream primed with the string (via UTF8). Personally, I doubt it will work - you are going to run into a lot of encoding issues treating raw binary as UTF8 data... I expect either the read or write (or both) to throw an exception.
这将创建一个以字符串(通过 UTF8)为基础的新 MemoryStream。就我个人而言,我怀疑它会起作用 - 您将遇到很多将原始二进制文件视为 UTF8 数据的编码问题......我希望读取或写入(或两者)都会引发异常。
(edit)
(编辑)
I should add that to work with base-64, simply get the data as a byte[], then call Convert.ToBase64String(...); and to get back the array, just use Convert.FromBase64String(...).
我应该添加它以使用 base-64,只需将数据作为 a 获取byte[],然后调用Convert.ToBase64String(...); 并取回数组,只需使用Convert.FromBase64String(...).
Re your edit, this is precisely what I tried to warn about above... in .NET, a string is not just a byte[], so you can't simply fill it with binary image data. A lot of the data simply won't make sense to the encoding, so might be quietly dropped (or an exception thrown).
重新编辑,这正是我在上面试图警告的内容...在.NET 中,字符串不仅仅是 a byte[],因此您不能简单地用二进制图像数据填充它。许多数据对编码根本没有意义,因此可能会被悄悄删除(或抛出异常)。
To handle raw binary (such as images) as strings, you need to use base-64 encoding; this adds size, however. Note that WebClientmight make this simpler, as it exposes byte[]functionality directly:
要将原始二进制(如图像)作为字符串处理,需要使用 base-64 编码;然而,这增加了尺寸。请注意,这WebClient可能会使这更简单,因为它byte[]直接公开功能:
using(WebClient wc = new WebClient()) {
byte[] raw = wc.DownloadData("http://www.google.com/images/nav_logo.png")
//...
}
Anyway, using a standard Streamapproach, here's how to encode and decode the base-64:
无论如何,使用标准Stream方法,以下是对 base-64 进行编码和解码的方法:
// ENCODE
// where "s" is our original stream
string base64;
// first I need the data as a byte[]; I'll use
// MemoryStream, as a convenience; if you already
// have the byte[] you can skip this
using (MemoryStream ms = new MemoryStream())
{
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = s.Read(buffer, 0, buffer.Length)) > 0)
{
ms.Write(buffer, 0, bytesRead);
}
base64 = Convert.ToBase64String(ms.GetBuffer(), 0, (int) ms.Length);
}
// DECODE
byte[] raw = Convert.FromBase64String(base64);
using (MemoryStream decoded = new MemoryStream(raw))
{
// "decoded" now primed with the binary
}
回答by Andrew Rollings
Will this work? I have no idea what format your string is in, so some massaging may be necessary.
这会起作用吗?我不知道您的字符串是什么格式,因此可能需要进行一些按摩。
Dim strAsBytes() as Byte = new System.Text.UTF8Encoding().GetBytes(Text)
Dim ms as New System.IO.MemoryStream(strAsBytes)
回答by TheSoftwareJedi
回答by Coder
var bytes = new byte[contents.Length * sizeof( char )];
Buffer.BlockCopy( contents.ToCharArray(), 0, bytes, 0, bytes.Length );
using( var stream = new MemoryStream( bytes ) )
{
// do your stuff with the stream...
}

