问题描述
我有一个数据:URI,我需要下载(读:负荷流或字节数组),使用普通的.Net Web客户端
/ 的WebRequest
。我该怎么办呢?
I have a data: URI that I need to "download" (read: load as a stream or byte array) using the normal .Net WebClient
/WebRequest
. How can I do that?
我需要这个,因为我需要显示SVG,其中包括使用的数据有些图像生成的XAML文件:URI的。我不想总是解析XAML,保存图像到磁盘,然后更改XAML指向的文件。我相信WPF使用的WebRequest
内部获得的图像。
I need this because I want to display a XAML file generated from SVG, which includes some images using data: URIs. I don't want to always parse the XAML, save the images to disk and then change the XAML to point to the files. I believe WPF uses WebRequest
internally to get those images.
推荐答案
您可以使用的做到这一点。您将需要实施 IWebRequestCreate
返回一个自定义的的WebRequest
返回一个自定义的 WebResponse类
,系统可最终用于获取从URI中的数据。它可能是这样的:
You can use WebRequest.RegisterPrefix()
to do that. You will need to implement IWebRequestCreate
that returns a custom WebRequest
that returns a custom WebResponse
, which can finally be used to get the data from the URI. It could look like this:
public class DataWebRequestFactory : IWebRequestCreate
{
class DataWebRequest : WebRequest
{
private readonly Uri m_uri;
public DataWebRequest(Uri uri)
{
m_uri = uri;
}
public override WebResponse GetResponse()
{
return new DataWebResponse(m_uri);
}
}
class DataWebResponse : WebResponse
{
private readonly string m_contentType;
private readonly byte[] m_data;
public DataWebResponse(Uri uri)
{
string uriString = uri.AbsoluteUri;
int commaIndex = uriString.IndexOf(',');
var headers = uriString.Substring(0, commaIndex).Split(';');
m_contentType = headers[0];
string dataString = uriString.Substring(commaIndex + 1);
m_data = Convert.FromBase64String(dataString);
}
public override string ContentType
{
get { return m_contentType; }
set
{
throw new NotSupportedException();
}
}
public override long ContentLength
{
get { return m_data.Length; }
set
{
throw new NotSupportedException();
}
}
public override Stream GetResponseStream()
{
return new MemoryStream(m_data);
}
}
public WebRequest Create(Uri uri)
{
return new DataWebRequest(uri);
}
}
这仅支持base64编码,但对于URI编码的支持,可以很容易地补充说。
This supports only base64 encoding, but support for URI encoding could be easily added.
然后注册它是这样的:
WebRequest.RegisterPrefix("data", new DataWebRequestFactory());
是的,这确实检索数据的工作:XAML文件中的图片
And yes, this does work for retrieving data: images in XAML files.
这篇关于如何与QUOT;下载"从数据:URI的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!