Web上のデータをByte配列で取得する

普段はWebから取得した画像ファイルを表示する場合は、Streamをコンストラクタ引数にしてBitmapオブジェクトを生成するんだけど、画像の保存とBitmapオブジェクトの生成の両方をしたかったので読み込んだストリームを一旦Byte配列として持たせて、上位層でこねこねしてもらう様にコードを書いてみた。

以下にサンプルコードを示す。

C#

  public byte[] GetBytes(string url)
  {
      byte[] bytes = null;
      try
      {
          HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(url);
          req.AllowAutoRedirect = false;
          req.UserAgent = _userAgent;
          req.Timeout = 30 * 1000;
 
          int contentLength, readedLength;
 
          using (MemoryStream memStrm = new MemoryStream())
          {
              using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
              {
                  contentLength = (int)res.ContentLength;
                  readedLength = 0;
 
                  using (System.IO.Stream strm = res.GetResponseStream())
                  {
                      while (readedLength < contentLength)
                      {
                          byte[] readBytes = new byte[Math.Min(256, contentLength)];
 
                          // ストリームからバッファの読み込み
                          int readed = strm.Read(readBytes, 0, readBytes.Length);
 
                          // バッファをメモリストリームへ書き込み
                          memStrm.Write(readBytes, 0, readed);
 
                          readedLength += readed;
                      }
                  }
              }
 
              // ストリームを頭に戻す
              memStrm.Seek(0, SeekOrigin.Begin);
 
              // byte配列の確保とストリームからの読み込み
              bytes = new byte[readedLength];
              memStrm.Read(bytes, 0, readedLength);
          }
      }
      catch
      {
          bytes = null;
      }
 
      return bytes;
  }