【发布时间】:2019-10-20 23:33:25
【问题描述】:
我正在制作一个应用程序,它将一些文件内容作为 c# 中的 html 写入服务器。问题是它应该可以工作,但不知何故却没有。
我已多次检查代码,从教程中复制了确切的代码并对其进行了修改以满足我的需要;但不知何故它仍然不起作用(即使它以前曾起作用)。
public Server(string filename)
{
chatNames = filename;
try
{
string content;
HttpListener server = new HttpListener();// this is the http server
server.IgnoreWriteExceptions = true;
server.Prefixes.Add("http://127.0.0.1/");
server.Prefixes.Add("http://localhost/");
server.Start();
while (true)
{
content = FileR(filename);
HttpListenerContext context = server.GetContext();
//context: provides access to httplistener's response
HttpListenerResponse response = context.Response;
//the response tells the server where to send the datas
string page = Directory.GetCurrentDirectory() + "/" + filename + ".txt";
//this will get the page requested by the browser
if (page == string.Empty) //if there's no page, we'll say it's index.html
page = "index.html";
TextReader tr = new StreamReader(page);
string msg = tr.ReadToEnd(); //getting the page's content
byte[] buffer = Encoding.UTF8.GetBytes(content);
//then we transform it into a byte array
response.ContentLength64 = buffer.Length; // set up the messasge's length
Stream st = response.OutputStream; // here we create a stream to send the message
st.Write(buffer, 0, buffer.Length); // and this will send all the content to the browser
context.Response.Close(); // here we close the connection
hasRan = true;
}
} catch (Exception e)
{
hasRan = false;
error = e.Message;
}
}
private string FileR(string name)
{
string content = string.Empty;
FileInfo fi = new FileInfo(chatNames);
if (IsFileLocked(fi))
{
using (StreamReader sr = new StreamReader(chatNames))
{
//viewMessage.TextAlignment = TextAlignment.Left;
content = sr.ReadToEnd();
}
}
else
{
content = "Please try again later";
Thread.Sleep(350);
}
return content;
}
我在网上到处寻找,但仍然找不到能回答我问题的东西。如果我在网上遗漏了什么,请通知。
【问题讨论】: