2013-02-08 38 views
0

我有一個數據:我需要使用正常的.Net WebClient/WebRequest「下載」(讀取:加載爲流或字節數組)的URI。我怎樣才能做到這一點?如何從數據中「下載」:URIs?

我需要這個,因爲我想顯示一個從SVG生成的XAML文件,其中包含一些使用data:URI的圖像。我不想總是解析XAML,將圖像保存到磁盤,然後將XAML更改爲指向文件。我相信WPF在內部使用WebRequest來獲取這些圖像。

回答

2

您可以使用WebRequest.RegisterPrefix()來做到這一點。您將需要實現IWebRequestCreate,該函數返回自定義WebRequest,該自定義返回自定義WebResponse,最終可用於從URI獲取數據。它可能看起來像這樣:

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編碼的支持。

你然後將其註冊這樣的:

WebRequest.RegisterPrefix("data", new DataWebRequestFactory()); 

是的,這並檢索數據的工作:在XAML文件的圖像。

+1

這個答案拯救了我的一天。在實現WebRequest類時也要重寫Icredentials。 – sms 2015-12-24 07:53:51