Search code examples
c#.nethttplistenersendfile

Serving Binary files using HttpLIstener


I am trying to make a httplistener server in c# that sends files to the client (who is on a browser). This is my code:

static void SendFile(HttpListenerResponse response, string FileName, string ContentType) {
    response.ContentType = ContentType;
    // Read contents of file
    var reader = new StreamReader(FileName);
    var contents = reader.ReadToEnd();
    reader.Close();
    // Write to output stream
    var writer = new StreamWriter(output);
    writer.Write(contents);
    // Wrap up.
    writer.Close();
    stream.Close();
    response.Close();
}

Unfortunately, this code cannot send binary files, such as images, PDFs, and lots of other file types. How can I make this SendFile function binary-safe?


Solution

  • Thank you for all the comments and the gist link! The solution where you read from the file as a byte[] and write those bytes to the output stream I looked up worked, but is was kind of confusing, so I made a really short SendFile function.

    static void SendFile(HttpListenerResponse response, string FileName, string ContentType) {
        response.AddHeader("Content-Type", ContentType);
        var output = response.OutputStream;
        // Open the file
        var file = new FileStream(FileName, FileMode.Open, FileAccess.Read);
        // Write to output stream
        file.CopyTo(output);
        // Wrap up.
        file.Close();
        stream.Close();
        response.Close();
    }
    

    This code just copies the file to the output stream.