用于接收文件的 HTTP 侦听器
本文关键字:HTTP 侦听器 文件 用于 | 更新日期: 2023-09-27 18:37:28
我正在尝试生成一个HTTP侦听器,该侦听器将接受文件并将其保存到某个位置。
下面的代码看到有东西进来,但没有保存文件。
如果您能查看代码并让我知道我哪里出错了,我将不胜感激。
class Program
{
static void Main(string[] args)
{
Listener();
}
public static void Listener()
{
const string prefix = "http://localhost:8082/";
var listener = new HttpListener();
listener.Prefixes.Add(prefix);
try
{
listener.Start();
}
catch (HttpListenerException hlex)
{
return;
}
while (listener.IsListening)
{
var context = listener.GetContext();
ProcessRequest(context);
}
listener.Close();
}
public static void ProcessRequest(HttpListenerContext context)
{
var filename = Path.GetFileName(context.Request.RawUrl);
var path = Path.Combine(@"c:'listenerFiles", filename);
try
{
context.Response.StatusCode = (int)HttpStatusCode.Accepted;
Console.WriteLine(context.Response.StatusCode = (int)HttpStatusCode.Accepted);
var receivingFile = File.ReadAllBytes(path);
Console.WriteLine(receivingFile);
context.Response.ContentLength64 = receivingFile.Length;
using (var s = context.Response.OutputStream)
s.Write(receivingFile, 0, receivingFile.Length);
}
catch (Exception e)
{
return;
}
}
}
当这得到文件时,它抛出的错误读取
未经授权访问执行
对路径"c:''listenerFiles"的访问被拒绝。
永远不要在不处理异常的情况下捕获异常! catch (Exception e){ return; }
只是被禁止!
在OutputStream
上使用using
是一个坏主意,因为它是在using
之后处理的,所以HTTP处理程序之后不能拾取它。取下using
,看看它是否有效。
还要检查 IIS 进程是否有权访问文件所在的路径。