WebRequest/WebResponse で Content-Length が不明のレスポンスが帰ってきた場合、WebResponse.ContentLength は -1。

書いてあってもおかしくないにもかかわらず、MSDN Library に記述がなかったので試した。以下実証コード。

using System;
using System.Net;

namespace WebRequestTest
{
    class Program
    {
        static void Main(string[] args)
        {
            if (args.Length > 0)
            {
                WebRequest request = WebRequest.Create(args[0]);
                WebResponse response = request.GetResponse();

                Console.WriteLine("Content-Length: {0}", response.ContentLength);
            }
            else
            {
                Console.Error.WriteLine("require argument(url)");
            }
        }
    }
}

結果

> telnet cho.half-done.net 80
GET /choweblobby.php HTTP/1.0
Host: cho.half-done.net

HTTP/1.1 200 OK
Date: Thu, 17 Jan 2008 12:10:21 GMT
Server: Apache
X-Powered-By: PHP/4.4.6
Connection: close
Content-Type: text/html ←Content-Length がない

(略)

>.\WebRequestTest.exe http://cho.half-done.net/choweblobby.php
Content-Length: -1