c#http文件服务器
时间: 2023-09-10 08:11:03 浏览: 54
要在 C# 中创建一个简单的 HTTP 文件服务器,可以使用 .NET 自带的 HttpListener 类。
以下是一个简单的示例代码:
```csharp
using System;
using System.IO;
using System.Net;
using System.Threading;
class HttpFileServer
{
static void Main(string[] args)
{
string directoryPath = @"C:\MyFiles"; // 文件目录路径
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/"); // 监听的地址和端口
listener.Start();
Console.WriteLine("Listening...");
while (true)
{
HttpListenerContext context = listener.GetContext();
ThreadPool.QueueUserWorkItem((o) =>
{
HttpListenerResponse response = context.Response;
string fileName = context.Request.Url.AbsolutePath.Substring(1); // 获取请求的文件名
string filePath = Path.Combine(directoryPath, fileName);
try
{
using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] buffer = new byte[4096];
int bytesRead;
response.ContentLength64 = stream.Length;
response.ContentType = "application/octet-stream";
response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
response.OutputStream.Write(buffer, 0, bytesRead);
}
}
}
catch (FileNotFoundException)
{
response.StatusCode = (int)HttpStatusCode.NotFound;
}
finally
{
response.Close();
}
}, null);
}
}
}
```
该示例代码监听地址为 `http://localhost:8080/`,并将文件目录路径设为 `C:\MyFiles`。当有 HTTP 请求时,程序会在线程池中开启一个新的线程来处理请求。如果请求的文件存在,则将该文件作为二进制流输出到响应中;如果请求的文件不存在,则返回状态码 404。