使用httplistener服务二进制文件

发布于 2025-02-08 15:45:29 字数 597 浏览 1 评论 0原文

我正在尝试在C#中制作httplistener服务器,该服务器将文件发送给客户端(浏览器上的人)。这是我的代码:

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();
}

不幸的是,此代码无法发送二进制文件,例如图像,PDF和许多其他文件类型。如何使此sendfile函数二进制安全?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

她如夕阳 2025-02-15 15:45:29

感谢您的所有评论和要点链接!您从文件中读取byte []并将这些字节写入我查找的输出流的解决方案,但很令人困惑,因此我做出了一个很短的sendfile函数。

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();
}

此代码仅将文件复制到输出流。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文