// HTTP 文件服务器 - 绿色工具箱 // C# 5.0 语法,零依赖。局域网内把文件夹变成可下载的网页,手机/其他电脑浏览器直接访问 // 用 HttpListener(Windows 自带),不监听外网,默认只绑当前网卡 using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Windows.Forms; namespace GreenToolbox { public class HttpServerToolForm : Form { private static readonly Color COL_GREEN = Color.FromArgb(0, 145, 88); private static readonly Color COL_BG = Color.White; private static readonly Color COL_PANEL = Color.FromArgb(245, 249, 246); private static readonly Color COL_GRAY = Color.FromArgb(120, 130, 124); private TextBox txtFolder; private TextBox txtPort; private Button btnStart; private Button btnStop; private Button btnPick; private Label lblUrls; private Label lblStatus; private HttpListener listener; private Thread serverThread; private volatile bool running; public HttpServerToolForm() { InitUi(); this.FormClosing += new FormClosingEventHandler(OnClosing); } private void InitUi() { this.Text = "HTTP 文件服务器 - 绿色工具箱"; this.Font = new Font("Microsoft YaHei UI", 9.5f); this.BackColor = COL_BG; this.ForeColor = Color.FromArgb(34, 40, 36); this.ClientSize = new Size(700, 430); this.MinimumSize = new Size(620, 400); int x = 22, y = 18; Label l0 = new Label(); l0.Text = "把一个文件夹变成局域网下载页:其他电脑/手机浏览器输入下方网址即可下载文件"; l0.AutoSize = true; l0.ForeColor = COL_GRAY; l0.Location = new Point(x, y); this.Controls.Add(l0); y += 34; Label lf = new Label(); lf.Text = "共享文件夹:"; lf.AutoSize = true; lf.Location = new Point(x, y + 5); this.Controls.Add(lf); txtFolder = new TextBox(); txtFolder.Location = new Point(x + 96, y); txtFolder.Size = new Size(450, 27); txtFolder.ReadOnly = true; txtFolder.BackColor = COL_PANEL; this.Controls.Add(txtFolder); btnPick = new Button(); btnPick.Text = "浏览"; btnPick.Location = new Point(x + 554, y - 1); btnPick.Size = new Size(110, 29); btnPick.FlatStyle = FlatStyle.Flat; btnPick.FlatAppearance.BorderColor = COL_GREEN; btnPick.ForeColor = Color.FromArgb(0, 110, 66); btnPick.Click += new EventHandler(PickClick); this.Controls.Add(btnPick); y += 42; Label lp = new Label(); lp.Text = "端口:"; lp.AutoSize = true; lp.Location = new Point(x, y + 5); this.Controls.Add(lp); txtPort = new TextBox(); txtPort.Location = new Point(x + 52, y); txtPort.Size = new Size(80, 27); txtPort.Text = "8080"; txtPort.Font = new Font("Consolas", 11f); this.Controls.Add(txtPort); btnStart = new Button(); btnStart.Text = "启动服务"; btnStart.Location = new Point(x + 150, y - 1); btnStart.Size = new Size(110, 29); btnStart.BackColor = COL_GREEN; btnStart.ForeColor = Color.White; btnStart.FlatStyle = FlatStyle.Flat; btnStart.FlatAppearance.BorderSize = 0; btnStart.Click += new EventHandler(StartClick); this.Controls.Add(btnStart); btnStop = new Button(); btnStop.Text = "停止"; btnStop.Location = new Point(x + 272, y - 1); btnStop.Size = new Size(90, 29); btnStop.Enabled = false; btnStop.FlatStyle = FlatStyle.Flat; btnStop.FlatAppearance.BorderColor = Color.FromArgb(200, 60, 60); btnStop.ForeColor = Color.FromArgb(180, 50, 50); btnStop.Click += new EventHandler(StopClick); this.Controls.Add(btnStop); lblStatus = new Label(); lblStatus.Text = "未启动"; lblStatus.Location = new Point(x + 380, y + 5); lblStatus.AutoSize = true; lblStatus.ForeColor = COL_GRAY; this.Controls.Add(lblStatus); y += 48; Label lu = new Label(); lu.Text = "访问地址(浏览器打开):"; lu.AutoSize = true; lu.Location = new Point(x, y); this.Controls.Add(lu); y += 26; lblUrls = new Label(); lblUrls.Text = "(启动后显示)"; lblUrls.Location = new Point(x, y); lblUrls.Font = new Font("Consolas", 11.5f); lblUrls.ForeColor = Color.FromArgb(0, 110, 66); lblUrls.AutoSize = true; this.Controls.Add(lblUrls); y += 44; Label lh = new Label(); lh.Text = "说明:\n· 仅限局域网访问,不会暴露到公网\n· 手机需与电脑连同一个 Wi-Fi\n· 第一次启动 Windows 可能弹防火墙提示,勾选\"专用网络\"允许即可\n· 文件直接以原始字节流返回,不做任何修改"; lh.Location = new Point(x, y); lh.ForeColor = COL_GRAY; lh.AutoSize = true; this.Controls.Add(lh); } private void PickClick(object sender, EventArgs e) { using (FolderBrowserDialog d = new FolderBrowserDialog()) { d.Description = "选择要共享的文件夹"; if (d.ShowDialog() == DialogResult.OK) txtFolder.Text = d.SelectedPath; } } private void StartClick(object sender, EventArgs e) { if (txtFolder.Text.Length == 0 || !Directory.Exists(txtFolder.Text)) { lblStatus.Text = "请先选择文件夹"; return; } int port; if (!int.TryParse(txtPort.Text.Trim(), out port) || port < 1024 || port > 65535) { lblStatus.Text = "端口范围 1024-65535"; return; } try { listener = new HttpListener(); listener.Prefixes.Add("http://+:" + port + "/"); listener.Start(); } catch { // 无管理员权限时 + 前缀会失败,降级为 localhost 提示 try { listener = new HttpListener(); listener.Prefixes.Add("http://127.0.0.1:" + port + "/"); listener.Start(); lblUrls.Text = "http://127.0.0.1:" + port + "/(受限:仅本机可访问)"; lblStatus.Text = "要其他设备访问,请以管理员身份运行一次"; } catch (Exception ex2) { lblStatus.Text = "启动失败:" + ex2.Message; return; } } running = true; serverThread = new Thread(ServerLoop); serverThread.IsBackground = true; serverThread.Start(); btnStart.Enabled = false; btnStop.Enabled = true; lblStatus.Text = "运行中…"; // 展示局域网地址 if (listener.Prefixes.Count > 0 && listener.Prefixes.ToString().Contains("+")) { List urls = new List(); urls.Add("http://" + GetLocalIp() + ":" + port + "/"); try { urls.Add("http://" + IPAddress.Loopback + ":" + port + "/"); } catch { } lblUrls.Text = string.Join(" ", urls.ToArray()); } else if (lblUrls.Text.Length == 0 || lblUrls.Text.StartsWith("(")) { lblUrls.Text = "http://127.0.0.1:" + port + "/(受限:仅本机可访问)"; } } private string GetLocalIp() { try { string host = Dns.GetHostName(); IPHostEntry entry = Dns.GetHostEntry(host); foreach (IPAddress ip in entry.AddressList) { if (ip.AddressFamily == AddressFamily.InterNetwork && !IPAddress.Loopback.Equals(ip)) return ip.ToString(); } } catch { } return "127.0.0.1"; } private void StopClick(object sender, EventArgs e) { StopServer(); } private void StopServer() { running = false; try { if (listener != null) listener.Stop(); } catch { } btnStart.Enabled = true; btnStop.Enabled = false; lblStatus.Text = "已停止"; } private void OnClosing(object sender, FormClosingEventArgs e) { running = false; try { if (listener != null) listener.Stop(); } catch { } } private void ServerLoop() { while (running) { HttpListenerContext ctx; try { ctx = listener.GetContext(); } catch { break; } try { HandleCtx(ctx); } catch { } } } private void HandleCtx(HttpListenerContext ctx) { HttpServerOps.Handle(ctx.Response, txtFolder.Text, ctx.Request.Url.AbsolutePath, delegate { return running; }); } } // ── 与界面解耦的纯逻辑,--selftest 直接调这里 ───────────────────────── public static class HttpServerOps { public static string HtmlEnc(string s) { if (s == null) return ""; return s.Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\"", """); } public static string FormatSize(long bytes) { if (bytes < 1024) return bytes + " B"; if (bytes < 1024 * 1024) return (bytes / 1024.0).ToString("0.#") + " KB"; if (bytes < 1024L * 1024 * 1024) return (bytes / 1024.0 / 1024).ToString("0.##") + " MB"; return (bytes / 1024.0 / 1024 / 1024).ToString("0.##") + " GB"; } // 把 URL 路径映射到磁盘文件;越界一律返回 null(不能只看 "..",还要防拼接后跑出根目录) public static string FullPath(string root, string rawPath) { if (root == null) return null; if (rawPath == null) rawPath = "/"; // 调用方通常已经 Unescape 过一遍,但这里自己再解两轮:%252e%252e 解一层还是 %2e%2e, // 只解一层的话 ".." 判不出来,等于给编码穿越留口子。 string p = rawPath; for (int i = 0; i < 2; i++) { string d; try { d = Uri.UnescapeDataString(p); } catch { break; } // 残缺的 % 序列就按字面处理 if (d == p) break; p = d; } if (p.IndexOf("..", StringComparison.Ordinal) >= 0) return null; string rel = p.TrimStart('/').Replace('/', Path.DirectorySeparatorChar); string rootAbs = Path.GetFullPath(root); string full = Path.GetFullPath(Path.Combine(rootAbs, rel)); if (full.Length == rootAbs.Length) return full; string prefix = rootAbs.EndsWith(Path.DirectorySeparatorChar.ToString()) ? rootAbs : rootAbs + Path.DirectorySeparatorChar; if (!full.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) return null; return full; } public static string ListHtml(string root, string rawPath) { string rel = (rawPath == null ? "" : rawPath).TrimStart('/'); string full = Path.Combine(root, rel.Replace('/', Path.DirectorySeparatorChar)); StringBuilder sb = new StringBuilder(); sb.Append("文件列表"); sb.Append("

文件列表

"); return sb.ToString(); } public static void SendText(HttpListenerResponse res, string html) { byte[] data = Encoding.UTF8.GetBytes(html); res.ContentType = "text/html; charset=utf-8"; res.ContentLength64 = data.Length; using (Stream os = res.OutputStream) os.Write(data, 0, data.Length); } public static void Handle(HttpListenerResponse res, string root, string absPath, Func isRunning) { string raw = Uri.UnescapeDataString(absPath == null ? "/" : absPath); string full = FullPath(root, raw); if (full == null) { SendText(res, "非法路径"); return; } if (Directory.Exists(full)) { SendText(res, ListHtml(root, raw)); return; } if (File.Exists(full)) { res.ContentType = "application/octet-stream"; res.AddHeader("Content-Disposition", "attachment; filename*=UTF-8''" + Uri.EscapeDataString(Path.GetFileName(full))); using (FileStream fs = new FileStream(full, FileMode.Open, FileAccess.Read, FileShare.Read)) { res.ContentLength64 = fs.Length; byte[] buf = new byte[64 * 1024]; int n; using (Stream os = res.OutputStream) { while ((n = fs.Read(buf, 0, buf.Length)) > 0) { os.Write(buf, 0, n); if (isRunning != null && !isRunning()) break; } } } return; } res.StatusCode = 404; SendText(res, "404 文件不存在"); } } // 命令行自测:不弹窗,纯逻辑 + 一次真实 HTTP 往返,退出码 0 = 全过,1 = 有失败 public static class SelfTest { private static int _pass = 0; private static int _fail = 0; private static List _lines = new List(); private static string Esc(string s) { if (s == null) return ""; if (s.Length > 90) s = s.Substring(0, 90) + "…"; return s.Replace("\r", "\\r").Replace("\n", "\\n"); } private static void Check(string name, string got, string want) { if (got == null) got = ""; if (want == null) want = ""; if (got == want) { _pass++; _lines.Add(" [ok] " + name); } else { _fail++; _lines.Add(" [!!] " + name + " 期望[" + Esc(want) + "] 实际[" + Esc(got) + "]"); } } private static string Fetch(string url, string[] meta) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url); req.Timeout = 5000; try { using (HttpWebResponse res = (HttpWebResponse)req.GetResponse()) using (Stream st = res.GetResponseStream()) using (MemoryStream ms = new MemoryStream()) { st.CopyTo(ms); meta[0] = ((int)res.StatusCode).ToString(); meta[1] = res.ContentType; meta[2] = res.Headers["Content-Disposition"] ?? ""; return Encoding.UTF8.GetString(ms.ToArray()); } } catch (WebException ex) { HttpWebResponse res = ex.Response as HttpWebResponse; meta[0] = res == null ? "-1" : ((int)res.StatusCode).ToString(); meta[1] = ""; meta[2] = ""; return ""; } } public static int Run(string dir) { if (string.IsNullOrEmpty(dir)) dir = Path.Combine(Path.GetTempPath(), "greentool-httpserver-selftest"); string root = Path.Combine(dir, "share"); string sub = Path.Combine(root, "sub"); HttpListener lis = null; try { Directory.CreateDirectory(root); Directory.CreateDirectory(sub); File.WriteAllText(Path.Combine(root, "hello.txt"), "HELLO 中文", new UTF8Encoding(false)); File.WriteAllText(Path.Combine(root, "报告.txt"), "报告内容", new UTF8Encoding(false)); _lines.Add("HTTP 文件服务器 自测(" + root + ")"); // ── HTML 转义 ── Check("尖括号引号都被转义", HttpServerOps.HtmlEnc("&\"x\""), "<b>&"x"</b>"); Check("空值不炸", HttpServerOps.HtmlEnc(null), ""); // ── 体积文案 ── Check("512 字节", HttpServerOps.FormatSize(512), "512 B"); Check("2 KB", HttpServerOps.FormatSize(2048), "2 KB"); Check("1.5 MB", HttpServerOps.FormatSize(1024L * 1024 * 3 / 2), "1.5 MB"); // ── 路径映射与穿越防护 ── string rootAbs = Path.GetFullPath(root); Check("根路径映射到共享目录本身", HttpServerOps.FullPath(root, "/"), rootAbs); Check("普通文件", HttpServerOps.FullPath(root, "/hello.txt"), Path.GetFullPath(Path.Combine(rootAbs, "hello.txt"))); Check("子目录里的文件", HttpServerOps.FullPath(root, "/sub/a.txt"), Path.GetFullPath(Path.Combine(rootAbs, "sub", "a.txt"))); Check("\"..\" 被拒", HttpServerOps.FullPath(root, "/../secret.txt") == null ? "null" : "passed", "null"); Check("变形穿越 /sub/../../x 被拒", HttpServerOps.FullPath(root, "/sub/../../x") == null ? "null" : "passed", "null"); Check("把 .. 编码成 %2e%2e 也被拒", HttpServerOps.FullPath(root, "/%2e%2e/secret.txt") == null ? "null" : "passed", "null"); Check("二次编码 %252e%252e 也被拒", HttpServerOps.FullPath(root, "/%252e%252e/secret.txt") == null ? "null" : "passed", "null"); Check("反斜杠写法 \\.. 被拒", HttpServerOps.FullPath(root, "/..\\secret.txt") == null ? "null" : "passed", "null"); Check("绝对路径 /C:/Windows 被拒", HttpServerOps.FullPath(root, "/C:/Windows/win.ini") == null ? "null" : "passed", "null"); // ── 目录列表 HTML ── string html = HttpServerOps.ListHtml(root, "/"); Check("首页列出了 hello.txt", html.Contains("hello.txt") ? "yes" : "no", "yes"); Check("首页没列出子目录(v1 不下钻)", html.Contains("sub") ? "yes" : "no", "no"); Check("列表里带体积", html.Contains("(12 B)") ? "yes" : "no", "yes"); string subHtml = HttpServerOps.ListHtml(root, "/sub"); Check("子目录页有空目录提示", subHtml.Contains("(空文件夹)") ? "yes" : "no", "yes"); Check("子目录页有上级链接", subHtml.Contains("..(上级)") ? "yes" : "no", "yes"); // ── 端到端:起一个只服务 5 次请求的真实 listener ── int port = 0; for (int attempt = 0; attempt < 6 && lis == null; attempt++) { int p = 35000 + new Random().Next(0, 9000); try { HttpListener l = new HttpListener(); l.Prefixes.Add("http://127.0.0.1:" + p + "/"); l.Start(); lis = l; port = p; } catch { } } if (lis == null) { _lines.Add(" [skip] 本机绑不上 127.0.0.1 端口(可能被安全策略拦),跳过真实 HTTP 往返"); } else { Thread th = new Thread(delegate() { for (int i = 0; i < 5; i++) { try { HttpListenerContext ctx = lis.GetContext(); HttpServerOps.Handle(ctx.Response, root, ctx.Request.Url.AbsolutePath, null); } catch { break; } } }); th.IsBackground = true; th.Start(); string baseUrl = "http://127.0.0.1:" + port + "/"; string[] meta = new string[3]; string body = Fetch(baseUrl + "hello.txt", meta); Check("下载内容与磁盘完全一致", body, "HELLO 中文"); Check("状态码 200", meta[0], "200"); Check("以附件形式返回(带 filename*)", meta[2].Contains("filename*=UTF-8''") ? "yes" : "no", "yes"); meta = new string[3]; Fetch(baseUrl + "nope.txt", meta); Check("不存在返回 404", meta[0], "404"); meta = new string[3]; string page = Fetch(baseUrl, meta); Check("首页能打开", meta[0], "200"); Check("首页是 UTF-8 HTML", meta[1].Contains("text/html") && meta[1].Contains("utf-8") ? "yes" : "no", "yes"); Check("首页列出文件", page.Contains("hello.txt") ? "yes" : "no", "yes"); meta = new string[3]; string cjk = Fetch(baseUrl + Uri.EscapeDataString("报告.txt"), meta); Check("中文文件名能下载", cjk, "报告内容"); try { lis.Stop(); } catch { } } } catch (Exception ex) { _fail++; _lines.Add(" [!!] 自测中途异常:" + ex.GetType().Name + " " + ex.Message); } finally { try { if (lis != null) lis.Stop(); } catch { } try { if (Directory.Exists(root)) Directory.Delete(root, true); } catch { } } _lines.Add(""); if (_fail == 0) _lines.Add("结果:共 " + (_pass + _fail) + " 项,全部通过 ✓"); else _lines.Add("结果:共 " + (_pass + _fail) + " 项,通过 " + _pass + ",失败 " + _fail + " ✗"); string all = string.Join("\r\n", _lines.ToArray()); Console.WriteLine(all); try { File.WriteAllText(Path.Combine(Directory.GetCurrentDirectory(), "selftest-httpserver.txt"), all, new UTF8Encoding(true)); } catch { } return _fail == 0 ? 0 : 1; } } static class Program { [STAThread] static void Main(string[] args) { if (args != null && args.Length > 0 && args[0] == "--selftest") { Environment.Exit(SelfTest.Run(args.Length >= 2 ? args[1] : null)); } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new HttpServerToolForm()); } } }