C# httplistener 提示文件被占用

今天把程序拷给zz的时候,结果程序一直异常结束,后来调试发现是httplisten的问题,抛出httplistenerException的异常,catch了一下,发现提示是The process cannot access the file because it is being used by another process.网上搜了下,发现是端口占用的问题,因为之前自己测试的时候用了10081,这个端口是分给服务端的,而且服务端正在zz的电脑上运行,结果就出现了上面的异常。这个提示可真是够坑爹的,怎么就成了file被占用了。
要实现该功能,您需要将以下步骤分解为更小的任务: 1. 创建一个HttpListener对象并开始监听请求 2. 接收POST请求并读取请求实体中的数据 3. 将接收到的数据保存到本地文件中 下面是一个示例代码,可以帮助您完成这些任务: ```csharp using System; using System.IO; using System.Net; class Program { static void Main(string[] args) { HttpListener listener = new HttpListener(); listener.Prefixes.Add("http://localhost:8080/"); listener.Start(); Console.WriteLine("Listening..."); while (true) { HttpListenerContext context = listener.GetContext(); HttpListenerRequest request = context.Request; if (request.HttpMethod == "POST") { // 获取请求实体中的数据 using (Stream inputStream = request.InputStream) { byte[] buffer = new byte[4096]; int bytesRead; string fileName = Path.GetFileName(request.Url.LocalPath); using (FileStream outputStream = File.Create(fileName)) { while ((bytesRead = inputStream.Read(buffer, 0, buffer.Length)) > 0) { outputStream.Write(buffer, 0, bytesRead); } } Console.WriteLine($"File saved as {fileName}"); } context.Response.StatusCode = 200; } else { context.Response.StatusCode = 405; } context.Response.Close(); } } } ``` 这段代码创建了一个`HttpListener`对象,它监听来自`http://localhost:8080/`的请求。当请求方法为`POST`时,它将请求实体中的数据保存到本地文件中。您可以使用Postman等工具向该地址发送POST请求并上传文件
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值