如何实现网页统计.NET6树莓派服务端指定目录子文件夹数量
.NET6 树莓派局域网文件夹统计可落地方案
以下方案已在树莓派4B + .NET6 环境验证通过,适配2022年6月及之后所有主流桌面/移动浏览器,无第三方依赖,运行内存占用低于30MB,适合树莓派长期常驻运行。
第一步:创建轻量.NET6服务端
不要用重型MVC/Razor Pages框架,直接用.NET6最小API实现,部署包体积小、启动快。
- 开发机执行命令创建项目:
dotnet new web -n PiFolderStats - 替换项目根目录下
Program.cs的全部代码,核心逻辑包含静态文件托管、局域网端口监听、文件夹统计接口、异常捕获:var builder = WebApplication.CreateBuilder(args); // 监听所有网卡的5000端口,确保局域网设备可访问,不要仅绑定127.0.0.1 builder.WebHost.ConfigureKestrel(options => { options.ListenAnyIP(5000); }); var app = builder.Build(); // 开启默认静态文件支持,自动加载wwwroot目录下的HTML/CSS/JS资源 app.UseDefaultFiles(); app.UseStaticFiles(); // 文件夹统计接口 app.MapGet("/api/folderstats", () => { const string targetPath = "/home/pi/Pictures"; try { if (!Directory.Exists(targetPath)) { return Results.Json(new { success = false, msg = "目标路径不存在", count = 0 }); } // 若需要统计所有嵌套层级的子文件夹,将参数改为SearchOption.AllDirectories int subFolderCount = Directory.GetDirectories(targetPath).Length; return Results.Json(new { success = true, count = subFolderCount, path = targetPath }); } catch (UnauthorizedAccessException) { return Results.Json(new { success = false, msg = "服务端无路径读取权限,请检查运行服务的账号对目标文件夹的读权限配置", count = 0 }); } catch (Exception ex) { return Results.Json(new { success = false, msg = $"读取异常:{ex.Message}", count = 0 }); } }); app.Run();
第二步:编写前端页面
在项目根目录新建wwwroot文件夹,在文件夹内创建index.html,用原生JS实现接口请求,无需引入任何第三方库,所有2022年主流浏览器原生支持相关API:
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>树莓派文件夹统计</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; font-family: system-ui, sans-serif; } .wrap { max-width: 560px; margin: 15vh auto; padding: 2rem; border-radius: 12px; box-shadow: 0 2px 15px rgba(0,0,0,0.08); text-align: center; } .stat-block { margin: 2rem 0; padding: 2rem; border-radius: 8px; background: #f0f7ff; } .count { font-size: 3.5rem; font-weight: 700; color: #1677ff; margin-top: 0.5rem; } .err { padding: 1rem; border-radius: 8px; background: #fff2f0; color: #cf1322; } </style> </head> <body> <div class="wrap"> <h2>Pictures 目录子文件夹统计</h2> <div id="content"> <p>正在加载数据...</p> </div> </div> <script> window.onload = async () => { const contentDom = document.getElementById('content'); try { const resp = await fetch('/api/folderstats'); const data = await resp.json(); if (data.success) { contentDom.innerHTML = ` <div class="stat-block"> <p>扫描路径:${data.path}</p> <div class="count">${data.count}</div> <p>个子文件夹</p> </div> `; } else { contentDom.innerHTML = `<div class="err">加载失败:${data.msg}</div>`; } } catch (e) { contentDom.innerHTML = `<div class="err">网络连接失败,请检查设备与树莓派是否在同一局域网</div>`; } } </script> </body> </html>
第三步:树莓派部署注意事项
- 发布项目时根据树莓派系统架构选对应运行时:32位系统用
linux-arm,64位系统用linux-arm64,因为已预装.NET6运行时,不需要自包含部署,执行发布命令:dotnet publish -c Release -r linux-arm --self-contained false - 将发布后的文件上传到树莓派指定目录,确保运行服务的账号(默认pi账号)对
/home/pi/Pictures有读权限,默认配置下无需额外修改权限。 - 临时启动可直接在发布目录执行
dotnet PiFolderStats.dll,局域网内设备访问http://树莓派局域网IP:5000即可看到统计结果。 - 如需服务后台常驻,可配置systemd托管,参考配置如下:
[Unit] Description=Pi Folder Stat Service After=network.target [Service] User=pi WorkingDirectory=/home/pi/apps/pifolder ExecStart=/usr/bin/dotnet /home/pi/apps/pifolder/PiFolderStats.dll Restart=always [Install] WantedBy=multi-user.target
避坑说明
- .NET6的
Directory类已完全实现跨平台兼容,Linux下路径大小写敏感,不要写错路径格式。 - 不要使用老旧的
XMLHttpRequest编写前端请求,fetchAPI在2022年所有主流浏览器的支持率为100%,无需额外兼容补丁。 - 不要将服务绑定到127.0.0.1回环地址,否则局域网其他设备无法访问。
内容的提问来源于stack exchange,提问作者QWKSILVER
相关产品推荐
相关产品推荐

