title: Content-Length Occasionally Wrong on Simple C# HTTP Server
body: <p>For some experimentation was working with Simple HTTP Server code <a href="http://www.codeproject.com/Articles/137979/Simple-HTTP-Server-in-C" rel="nofollow">here</a></p>
  
  <p>In one case I wanted it to serve some ANSI encoded text configuration files. I am aware there are more issues with this code but the only one I'm currently concerned with is Content-Length is wrong, but only for certain text files.</p>
  
  <p>Example code:</p>
  
  <p>Output stream initialisation:</p>
  
  <pre><code>outputStream = new StreamWriter(new BufferedStream(socket.GetStream()));
  </code></pre>
  
  <p>The handling of HTTP get:</p>
  
  <pre><code>public override void handleGETRequest(HttpProcessor p)
  {
  
      if (p.http_url.EndsWith(".pac"))
      {
          string filename = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), p.http_url.Substring(1));
          Console.WriteLine(string.Format("HTTP request for : {0}", filename));
          if (File.Exists(filename))
          {
              FileInfo fi = new FileInfo(filename);
              DateTime lastWrite = fi.LastWriteTime;
  
              Stream fs = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
              StreamReader sr = new StreamReader(fs);
              string result = sr.ReadToEnd().Trim();
              Console.WriteLine(fi.Length);
              Console.WriteLine(result.Length);
              p.writeSuccess("application/x-javascript-config",result.Length,lastWrite);
              p.outputStream.Write(result);
              // fs.CopyTo(p.outputStream.BaseStream);
              p.outputStream.BaseStream.Flush();
              fs.Close();
          }
          else
          {
              Console.WriteLine("404 - FILE not found!");
              p.writeFailure();
          }
      }
  
  }  
  
     public void writeSuccess(string content_type,long length,DateTime lastModified) {
              outputStream.Write("HTTP/1.0 200 OK\r\n");            
              outputStream.Write("Content-Type: " + content_type + "\r\n");
              outputStream.Write("Last-Modified: {0}\r\n", lastModified.ToUniversalTime().ToString("r"));
              outputStream.Write("Accept-Range: bytes\r\n");
              outputStream.Write("Server: FlakyHTTPServer/1.3\r\n");
              outputStream.Write("Date: {0}\r\n", DateTime.Now.ToUniversalTime().ToString("r"));
              outputStream.Write(string.Format("Content-Length: {0}\r\n\r\n", length));   
                }
  </code></pre>
  
  <p>For most files I've tested with Content-Length is correct. However when testing with HTTP debugging tool <a href="http://www.telerik.com/fiddler" rel="nofollow">Fiddler</a> some times protocol violation is reported on Content-Length.</p>
  
  <p>For example fiddler says:</p>
  
  <p>Request Count:   1
  Bytes Sent:      303        (headers:303; body:0)
  Bytes Received:  29,847     (headers:224; body:29,623)</p>
  
  <p>So Content-Length should be 29623. But the HTTP header generated is </p>
  
  <pre><code>Content-Length: 29617
  </code></pre>
  
  <p>I saved the body of HTTP content from Fiddler and visibly compared the files, couldn't notice any difference. Then loaded them into BeyondCompare Hex compare, there are several problems with files like this:</p>
  
  <pre><code>Original File: 2D 2D 96       20 2A 2F
  HTTP Content : 2D 2D EF BF BD 20 2A 2F
  
  Original File: 27 3B 0D 0A 09 7D 0D 0A 0D 0A 09
  HTTP Content : 27 3B    0A 09 7D    0A    0A 09
  </code></pre>
  
  <p>I suspect problem is related to encoding but not exactly sure. Only serving ANSI encoded files, no Unicode. </p>
  
  <p>I made the file serve correctly with right Content-Length by modifying parts of the file with bytes sequence. Made this change in 3 parts of the file:</p>
  
  <pre><code>2D 2D 96 (--–) to 2D 2D 2D (---)
  </code></pre>