使用httplistener服务二进制文件
我正在尝试在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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
感谢您的所有评论和要点链接!您从文件中读取
byte []
并将这些字节写入我查找的输出流的解决方案,但很令人困惑,因此我做出了一个很短的sendfile函数。此代码仅将文件复制到输出流。
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.This code just copies the file to the output stream.