C# HttpListener 接收到大型word文档保存到本地文件,如果有当前名称的文件则替换,如果没有则新建
时间: 2023-12-04 18:05:50 浏览: 126
你可以使用以下代码来实现:
```csharp
using System;
using System.IO;
using System.Net;
using System.Text;
public class FileServer
{
private HttpListener listener;
public FileServer(string url)
{
listener = new HttpListener();
listener.Prefixes.Add(url);
}
public void Start()
{
listener.Start();
Console.WriteLine("Listening...");
while (true)
{
try
{
HttpListenerContext context = listener.GetContext();
ProcessRequest(context);
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
private void ProcessRequest(HttpListenerContext context)
{
if (context.Request.HttpMethod == "POST")
{
string filename = context.Request.Headers["Filename"];
if (string.IsNullOrEmpty(filename))
{
context.Response.StatusCode = 400;
context.Response.StatusDescription = "Missing filename header";
context.Response.Close();
return;
}
string filePath = Path.Combine(Environment.CurrentDirectory, filename);
if (File.Exists(filePath))
{
File.Delete(filePath);
}
using (FileStream fileStream = new FileStream(filePath, FileMode.CreateNew))
{
context.Request.InputStream.CopyTo(fileStream);
}
context.Response.StatusCode = 200;
context.Response.StatusDescription = "OK";
context.Response.Close();
}
else
{
context.Response.StatusCode = 405;
context.Response.StatusDescription = "Method not allowed";
context.Response.Close();
}
}
}
```
然后在你的主函数中启动文件服务器并监听端口,如下所示:
```csharp
static void Main(string[] args)
{
FileServer server = new FileServer("http://localhost:8080/");
server.Start();
}
```
当收到 POST 请求时,服务器会从请求头中获取文件名,检查当前目录下是否已有同名文件,如果有则删除,然后将请求正文保存到本地文件中。如果没有同名文件,则直接创建新文件。
阅读全文