C# HttpListener 接收到docx保存到本地文件,如果有当前名称的文件则替换,如果没有则新建
时间: 2023-12-04 10:05:36 浏览: 44
可以按照以下步骤实现:
1. 首先,你需要在代码中实例化一个 `HttpListener` 对象,用于接收来自客户端的请求。你可以指定监听的端口号和 URL 前缀,如下所示:
```csharp
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
```
2. 接下来,你需要启动 `HttpListener` 对象,开始监听来自客户端的请求。可以使用 `Start()` 方法来启动它:
```csharp
listener.Start();
```
3. 然后,在一个无限循环中等待客户端请求,可以使用 `GetContext()` 方法来获取客户端请求的上下文信息。在这个上下文信息中包含了客户端请求的所有信息,包括请求的 URL、请求的头部信息、请求的数据等等:
```csharp
while (true)
{
HttpListenerContext context = listener.GetContext();
// 处理客户端请求
}
```
4. 在处理客户端请求时,如果请求的是一个 `docx` 文件,那么你需要从请求中获取文件数据,并将其保存到本地文件中。可以使用 `Request.InputStream` 属性来获取请求数据,然后使用 `File.WriteAllBytes()` 方法将数据写入到本地文件中。如果本地已经存在同名文件,则可以使用 `File.Delete()` 方法删除原有文件,再进行保存:
```csharp
if (context.Request.Url.LocalPath.EndsWith(".docx"))
{
string fileName = Path.GetFileName(context.Request.Url.LocalPath);
string filePath = Path.Combine(@"C:\temp", fileName);
if (File.Exists(filePath))
{
File.Delete(filePath);
}
using (var fileStream = File.Create(filePath))
{
context.Request.InputStream.CopyTo(fileStream);
}
context.Response.StatusCode = 200;
context.Response.Close();
}
```
5. 最后,记得在程序退出之前停止 `HttpListener` 对象的监听,可以使用 `Stop()` 方法来停止:
```csharp
listener.Stop();
```
完整的代码示例如下:
```csharp
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://localhost:8080/");
listener.Start();
while (true)
{
HttpListenerContext context = listener.GetContext();
if (context.Request.Url.LocalPath.EndsWith(".docx"))
{
string fileName = Path.GetFileName(context.Request.Url.LocalPath);
string filePath = Path.Combine(@"C:\temp", fileName);
if (File.Exists(filePath))
{
File.Delete(filePath);
}
using (var fileStream = File.Create(filePath))
{
context.Request.InputStream.CopyTo(fileStream);
}
context.Response.StatusCode = 200;
context.Response.Close();
}
}
listener.Stop();
```
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)