1

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?

Caleb Liu
  • 627
  • 5
  • 18
  • 1
    Why are you using a `StreamReader`? Most "reader" classes (aside from `BinaryReader`, which you don't need) are intended to interoperate with strings. Just get rid of `StreamReader` and interact with the streams directly and you'll solve your problem. – Kirk Woll Jun 19 '22 at 13:18
  • Where is httplistener? And this code just copies a file to another stream. – shingo Jun 19 '22 at 13:22
  • 1
    To return binary files, your code needs to return `byte[]` and also set the `Content-Type` response header, so that the client or browser can handle the file download. See this SO [answer](https://stackoverflow.com/a/13386573/14973743) to get a good idea. – Anand Sowmithiran Jun 19 '22 at 13:46
  • 1
    Here is a very appropriate example of httpListener sending back files as HttpResponse, [gist link](https://gist.github.com/abc126/40906c32d4f076ab26e1228294638339) – Anand Sowmithiran Jun 19 '22 at 13:51

1 Answers1

0

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.

Caleb Liu
  • 627
  • 5
  • 18