在 .NET MiniAPI (Kestrel) 中实现静态文件服务 + 可排序目录浏览功能

在开发轻量级 API 时,.NET MiniAPI 凭借其简洁高效的特性成为首选。但实际场景中,我们常需要暴露静态文件(如 API 文档、配置文件、共享资源),甚至允许客户端浏览目录下的文件列表。默认情况下,MiniAPI 的静态文件服务不支持目录浏览,且原生目录列表无排序功能,本文将详细记录如何实现「指定目录暴露 + 目录浏览 + 列表排序」的完整方案,附完整代码和优化细节。

一、需求背景

在 MiniAPI 中实现以下核心功能:

  1. 暴露服务器上的指定物理目录(如 GeoIP 文件夹),支持客户端通过 URL 访问文件;
  2. 启用目录浏览功能,允许客户端列出目录下的文件/子目录;
  3. 目录列表支持按「名称、大小、修改时间」排序(点击表头切换升序/降序);
  4. 优化目录列表样式,保持简洁易用,同时兼容 AOT 编译。

二、实现步骤(基于 .NET MiniAPI > 8.0)

1. 环境准备

创建 .NET MiniAPI 项目(若已有项目可跳过):

dotnet new web -n MiniApiStaticFileDemo
cd MiniApiStaticFileDemo

2. 核心配置:暴露指定物理目录 + 启用目录浏览

Program.cs 中配置静态文件中间件和目录浏览功能,核心是指定物理目录、URL 访问路径,并关联自定义排序格式化器。

2.1 Program.cs 完整配置

using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.FileProviders;
using System.Text;

var builder = WebApplication.CreateSlimBuilder(args);
var app = builder.Build();

// 关键配置:指定要暴露的物理目录
string baseDir = AppContext.BaseDirectory; // 程序运行目录
string exposeDir = Path.Combine(baseDir, "GeoIP"); // 要暴露的目录(如 GeoIP 文件夹)
string urlPrefix = "/geoip"; // 客户端访问前缀(通过 /geoip 访问该目录)

// 1. 配置静态文件服务:暴露指定物理目录
app.UseStaticFiles(new StaticFileOptions
{
    FileProvider = new PhysicalFileProvider(exposeDir), // 物理目录路径
    RequestPath = urlPrefix, // URL 访问路径(例:http://localhost:5000/geoip/文件名称)
    OnPrepareResponse = ctx =>
    {
        // 可选:添加响应头,禁止缓存静态文件
        ctx.Context.Response.Headers.Append("Cache-Control", "no-cache, no-store");
    }
});

// 2. 启用目录浏览(默认禁用),并关联自定义排序格式化器
app.UseDirectoryBrowser(new DirectoryBrowserOptions
{
    FileProvider = new PhysicalFileProvider(exposeDir),
    RequestPath = urlPrefix, // 与静态文件访问路径保持一致
    Formatter = new SortableDirectoryFormatter("GeoIP 目录列表") // 自定义格式化器(支持排序)
});

// 测试接口
app.MapGet("/", () => Results.Ok("MiniAPI 静态文件服务 + 可排序目录浏览已启用"));

app.Run("http://*:5000");

3. 关键实现:自定义可排序目录格式化器

默认的目录浏览列表无排序功能,且样式简陋。我们通过实现 IDirectoryFormatter 接口,自定义目录列表的 HTML 输出,添加「名称、大小、修改时间」排序功能,同时优化样式和安全性。

3.1 完整 SortableDirectoryFormatter 类

创建 SortableDirectoryFormatter.cs 文件,核心功能包括:

  • 过滤隐藏文件(以 . 开头的文件);
  • 目录在前、文件在后的默认排序;
  • 点击表头切换排序方向(升序/降序);
  • 支持按名称、文件大小、修改时间排序;
  • XSS 防护、跨平台路径处理。
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.FileProviders;
using System.Globalization;
using System.Text;

public class SortableDirectoryFormatter : IDirectoryFormatter
{
    private readonly string _pageTitle;
    // 时间格式:年-月-日 时:分:秒(UTC 时区)
    private const string CustomDateTimeFormat = "yyyy-MM-dd HH:mm:ss +00:00";

    // 构造函数:支持自定义页面标题
    public SortableDirectoryFormatter(string pageTitle = "目录列表")
    {
        _pageTitle = pageTitle ?? "目录列表";
    }

    public async Task GenerateContentAsync(HttpContext context, IEnumerable<IFileInfo> contents)
    {
        // 1. 过滤隐藏文件 + 初始排序(目录在前,文件在后)
        var safeContents = contents ?? Enumerable.Empty<IFileInfo>();
        var fileList = new List<IFileInfo>(safeContents.Where(f =>
            !string.IsNullOrEmpty(f.Name) && !f.Name.StartsWith(".")
        ));
        fileList.Sort((a, b) =>
        {
            if (a.IsDirectory != b.IsDirectory)
                return a.IsDirectory ? -1 : 1;
            return string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase);
        });

        // 2. 生成面包屑导航(支持多层目录跳转)
        var breadcrumbBuilder = new StringBuilder();
        string currentPath = "/";
        breadcrumbBuilder.Append($"<a href=\"{HtmlEncode(currentPath)}\">/</a>");
        var requestPath = context.Request.Path.Value;
        if (!string.IsNullOrEmpty(requestPath))
        {
            var pathSegments = requestPath.Split('/', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries);
            foreach (var segment in pathSegments)
            {
                currentPath = Path.Combine(currentPath, segment + "/").Replace(Path.DirectorySeparatorChar, '/');
                breadcrumbBuilder.Append($"<a href=\"{HtmlEncode(currentPath)}\">{HtmlEncode(segment)}/</a>");
            }
        }

        // 3. 构建 HTML 页面(含样式 + 排序脚本)
        var htmlBuilder = new StringBuilder(4096);
        htmlBuilder.AppendLine("<!DOCTYPE html>");
        htmlBuilder.AppendLine("<html lang=\"zh-CN\">");
        htmlBuilder.AppendLine("<head>");
        htmlBuilder.AppendLine($"<title>{_pageTitle} - {HtmlEncode(requestPath ?? "/")}</title>");
        // 样式:保持简洁,适配不同设备
        htmlBuilder.AppendLine(@"<style>
            body { font-family: ""Segoe UI"", ""Microsoft YaHei"", sans-serif; font-size: 14px; max-width: 1200px; margin: 0 auto; padding: 20px; }
            header h1 { font-size: 24px; font-weight: 400; margin: 0 0 20px 0; color: #333; }
            #index { width: 100%; border-collapse: separate; border-spacing: 0; border: 1px solid #eee; }
            #index th { background: #f8f9fa; padding: 10px; text-align: center; cursor: pointer; user-select: none; position: relative; border-bottom: 2px solid #ddd; }
            #index td { padding: 8px 10px; border-bottom: 1px solid #eee; }
            #index th:hover { background: #f1f3f5; }
            #index td.length, td.modified { text-align: right; }
            a { color: #127aac; text-decoration: none; }
            a:hover { color: #13709e; text-decoration: underline; }
            .sort-arrow { position: absolute; right: 8px; font-size: 0.8em; color: #999; }
            .dir-name { font-weight: 500; }
        </style>");
        htmlBuilder.AppendLine("</head>");
        htmlBuilder.AppendLine("<body>");
        htmlBuilder.AppendLine($"<header><h1>{_pageTitle}:{breadcrumbBuilder}</h1></header>");
        htmlBuilder.AppendLine("<table id=\"index\">");
        htmlBuilder.AppendLine("<thead><tr>");
        htmlBuilder.AppendLine("<th data-col=\"name\">名称 <span class=\"sort-arrow\">↑</span></th>");
        htmlBuilder.AppendLine("<th data-col=\"size\">大小 <span class=\"sort-arrow\"></span></th>");
        htmlBuilder.AppendLine("<th data-col=\"modified\">最后修改时间 <span class=\"sort-arrow\"></span></th>");
        htmlBuilder.AppendLine("</tr></thead><tbody>");

        // 4. 生成文件/目录列表行
        if (fileList.Count == 0)
        {
            htmlBuilder.AppendLine("<tr><td colspan=\"3\" style=\"text-align:center; padding:20px; color:#666;\">目录无可用文件</td></tr>");
        }
        else
        {
            foreach (var file in fileList)
            {
                var fileName = file.IsDirectory ? $"{file.Name}/" : file.Name;
                var fileClass = file.IsDirectory ? "dir-name" : "";
                var fileSize = file.IsDirectory ? "-" : FormatFileSizeWithComma(file.Length);
                var fileModified = file.LastModified.ToUniversalTime().ToString(CustomDateTimeFormat, CultureInfo.InvariantCulture);
                var encodedFileName = Uri.EscapeDataString(file.Name);
                var fileUrl = $"{context.Request.Path}/{encodedFileName}".Replace("//", "/");

                htmlBuilder.AppendLine("<tr>");
                htmlBuilder.AppendLine($"<td class=\"name {fileClass}\"><a href=\"{HtmlEncode(fileUrl)}\">{HtmlEncode(fileName)}</a></td>");
                htmlBuilder.AppendLine($"<td class=\"length\">{HtmlEncode(fileSize)}</td>");
                htmlBuilder.AppendLine($"<td class=\"modified\">{HtmlEncode(fileModified)}</td>");
                htmlBuilder.AppendLine("</tr>");
            }
        }

        htmlBuilder.AppendLine("</tbody></table>");
        // 5. 排序核心脚本(点击表头切换排序)
        htmlBuilder.AppendLine(@"<script>
            document.addEventListener('DOMContentLoaded', function() {
                const table = document.getElementById('index');
                if (!table) return;
                const headers = table.querySelectorAll('thead th[data-col]');
                const tbody = table.querySelector('tbody');
                let currentSort = { col: 'name', order: 'asc' };

                // 表头点击事件
                headers.forEach(th => {
                    th.addEventListener('click', function() {
                        const newCol = this.dataset.col;
                        currentSort.order = (currentSort.col === newCol) ? (currentSort.order === 'asc' ? 'desc' : 'asc') : 'asc';
                        currentSort.col = newCol;
                        updateSortArrows();
                        sortTable();
                    });
                });

                // 更新排序箭头
                function updateSortArrows() {
                    headers.forEach(th => {
                        const arrow = th.querySelector('.sort-arrow');
                        arrow.textContent = (th.dataset.col === currentSort.col) ? (currentSort.order === 'asc' ? '↑' : '↓') : '';
                    });
                }

                // 排序逻辑
                function sortTable() {
                    const rows = Array.from(tbody.querySelectorAll('tr'));
                    if (!rows.length) return;

                    rows.sort((a, b) => {
                        const cellA = a.querySelector(`td.${getCellClass(currentSort.col)}`).textContent.trim();
                        const cellB = b.querySelector(`td.${getCellClass(currentSort.col)}`).textContent.trim();

                        switch (currentSort.col) {
                            case 'name':
                                const isDirA = cellA.endsWith('/');
                                const isDirB = cellB.endsWith('/');
                                if (isDirA !== isDirB) return isDirA ? -1 : 1;
                                return currentSort.order === 'asc' ? cellA.localeCompare(cellB, 'zh-CN') : cellB.localeCompare(cellA, 'zh-CN');
                            case 'size':
                                if (cellA === '-') return -1;
                                if (cellB === '-') return 1;
                                const sizeA = BigInt(cellA.replace(/,/g, ''));
                                const sizeB = BigInt(cellB.replace(/,/g, ''));
                                return currentSort.order === 'asc' ? (sizeA < sizeB ? -1 : 1) : (sizeA > sizeB ? -1 : 1);
                            case 'modified':
                                const dateA = new Date(cellA.replace(' +00:00', 'Z')).getTime();
                                const dateB = new Date(cellB.replace(' +00:00', 'Z')).getTime();
                                return currentSort.order === 'asc' ? (dateA - dateB) : (dateB - dateA);
                            default: return 0;
                        }
                    });

                    tbody.innerHTML = '';
                    rows.forEach(row => tbody.appendChild(row));
                }

                function getCellClass(colName) {
                    return colName === 'name' ? 'name' : colName === 'size' ? 'length' : 'modified';
                }

                updateSortArrows();
            });
        </script>");
        htmlBuilder.AppendLine("</body></html>");

        // 输出响应
        context.Response.ContentType = "text/html; charset=utf-8";
        await context.Response.WriteAsync(htmlBuilder.ToString(), Encoding.UTF8);
    }

    // 辅助方法:文件大小格式化(带千分位)
    private static string FormatFileSizeWithComma(long bytes)
    {
        return bytes.ToString("N0", CultureInfo.InvariantCulture);
    }

    // 辅助方法:HTML 编码(防 XSS)
    private static string HtmlEncode(string value)
    {
        if (string.IsNullOrEmpty(value)) return string.Empty;
        return value.Replace("&", "&amp;")
                    .Replace("<", "&lt;")
                    .Replace(">", "&gt;")
                    .Replace("\"", "&quot;")
                    .Replace("'", "&#39;")
                    .Replace("`", "&#96;");
    }
}

4. 核心功能说明

4.1 静态文件服务配置

  • PhysicalFileProvider(exposeDir):指定要暴露的物理目录(如 GeoIP 文件夹,位于程序运行目录下);
  • RequestPath = "/geoip":客户端通过 http://localhost:5000/geoip/文件名 访问文件;
  • OnPrepareResponse:可选配置,添加缓存控制头,避免浏览器缓存静态文件。

4.2 目录浏览功能

  • UseDirectoryBrowser:启用目录浏览(默认禁用),需与静态文件服务的 FileProviderRequestPath 保持一致;
  • SortableDirectoryFormatter:自定义目录列表格式化器,替代默认的简陋列表,支持排序和样式优化。

4.3 排序功能实现

  • 前端:通过 JavaScript 监听表头点击事件,切换排序字段(名称/大小/修改时间)和排序方向(升序/降序);
  • 排序逻辑:
    • 名称排序:目录优先,文件在后,按字母/中文拼音排序;
    • 大小排序:目录显示 -,文件按数值大小排序(去除千分位逗号);
    • 时间排序:将 UTC 时间转换为时间戳排序,兼容 2025-10-18 08:16:06 +00:00 格式。

三、关键优化点(兼容生产环境)

1. 安全性优化

  • XSS 防护:通过 HtmlEncode 方法对文件名、路径等用户可控内容进行编码,避免脚本注入;
  • 隐藏文件过滤:默认过滤以 . 开头的文件(如 .gitignore.env),防止敏感文件泄露;
  • 可选:添加身份认证(如 API Key、JWT),限制目录浏览权限(例:RequireAuthorization())。

2. 兼容性优化

  • 跨平台支持:使用 Path.Combine 和路径分隔符替换,兼容 Windows/Linux/macOS;
  • AOT 编译兼容:避免反射和动态代码,支持 .NET 8+ AOT 编译(可直接发布为原生可执行文件);
  • 空值安全:处理 contentsnull、文件名为空等异常场景,避免程序崩溃。

3. 体验优化

  • 面包屑导航:支持多层目录跳转(如 /geoip/GeoLite2/),方便用户回溯;
  • 时间格式标准化:统一使用 yyyy-MM-dd HH:mm:ss +00:00 格式,避免时区混淆;
  • 响应头优化:指定 charset=utf-8,确保中文文件名正常显示。

四、测试效果

  1. 运行项目:dotnet run
  2. 在程序运行目录下创建 GeoIP 文件夹,放入测试文件/子目录;
  3. 访问 http://localhost:5000/geoip,即可看到目录列表:
    1. 默认按名称升序排列,目录在前,文件在后;
    2. 点击表头「名称」「大小」「最后修改时间」可切换排序方式;
    3. 点击文件名/目录名可直接访问(目录会进入下一级列表)。

五、扩展场景

  1. 静态资源托管:用于托管 API 文档(如 Swagger、Redoc)、前端静态文件(Vue/React 构建产物);
  2. 内部文件共享:团队内部临时共享文件(结合身份认证,避免公开访问);
  3. 日志文件查看:暴露日志目录,支持按修改时间排序查看最新日志文件。

六、总结

通过 .NET MiniAPI 的静态文件中间件 + 自定义目录格式化器,我们仅需少量代码就实现了「指定目录暴露 + 可排序目录浏览」功能。该方案简洁高效,兼容生产环境,适用于轻量级文件服务场景。如需进一步增强,可扩展权限控制、文件上传、下载限速等功能。

下载 Demo : MiniApiStaticFileDemo.zip

如果有任何问题或优化建议,欢迎在评论区交流~

使用 HttpRepl 浏览、测试 Web API

The HTTP Read-Eval-Print Loop (REPL) 

  • 一种轻量级跨平台命令行工具,在所有支持的 .NET Core 的位置都可得到支持。
  • 用于发出 HTTP 请求以测试 ASP.NET Core Web API(和非 ASP.NET Core web API)并查看其结果。
  • 可以在任何环境下测试托管的 web API,包括 localhost 和 Azure 应用服务。

安装:dotnet tool install -g Microsoft.dotnet-httprepl

(视频)使用 HttpRepl 浏览 Web API:

https://learn.microsoft.com/zh-cn/shows/beginners-series-to-web-apis/exploring-web-apis-with-the-httprepl-16-of-18–beginners-series-to-web-apis

使用 HttpRepl 测试 Web API

https://learn.microsoft.com/zh-cn/aspnet/core/web-api/http-repl/?view=aspnetcore-8.0&tabs=windows

HttpRepl:用于与 RESTful HTTP 服务交互的命令行工具

https://devblogs.microsoft.com/dotnet/httprepl-a-command-line-tool-for-interacting-with-restful-http-services/#configure-visual-studio-for-windows-to-launch-httprepl-on-f5

HttpRepl GitHub 存储库https://github.com/dotnet/HttpRepl

在 .Net 6/7 中修改配置让生成项目时版本号自增长

项目里先添加一个“程序集信息文件” :AssemblyInfo.cs

[assembly: AssemblyVersion("1.0.0.*")] //修订号为*
//[assembly: AssemblyFileVersion("1.0.0.0")] //此行文件版本注释掉

双击项目文件,进行编辑,在<PropertyGroup>节点中加入以下内容:

<!-- 自定义版本开关-->
		<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
		<Deterministic>False</Deterministic>

		<VersionSuffix>1.0.1.$([System.DateTime]::UtcNow.ToString(mmff))</VersionSuffix>
		<AssemblyVersion Condition=" '$(VersionSuffix)' == '' ">0.0.0.1</AssemblyVersion>
		<AssemblyVersion Condition=" '$(VersionSuffix)' != '' ">$(VersionSuffix)</AssemblyVersion>
		<Version Condition=" '$(VersionSuffix)' == '' ">0.0.1.0</Version>
		<Version Condition=" '$(VersionSuffix)' != '' ">$(VersionSuffix)</Version>
<!-- 自定义版本开关-->

然后生成就行了,每次文件版本最后的修订号根据时间递增。

我个人是这样用的,也可以按自己习惯自己改下。

解决VS2019/VsCode 错误提示 No SDKs were found.

装了 .net core 5.0的SDK,在VS2019建了个项目,打开发现解决方案中是空的。换VScode也是提示: No SDKs were found.

CMD下 “dotnet –info”,.NET SDKs 下没有条目,只有.NET runtimes。

发现问题在于环境变量的path设置:

原先的是:”C:\Program Files (x86)\dotnet” ,但目录下没有SDK文件夹

应该添加路径:“C:\Program Files\dotnet” ,此目录下有SDK

添加过问题依然。

原来应用程序会去环境变量path条目的目录中,按顺序,查找“dotnet.exe”,在”C:\Program Files (x86)\dotnet”找到一个,就停止寻找下面的路径条目,

所以“C:\Program Files\dotnet”,要放在 “C:\Program Files (x86)\dotnet”之前。

在环境变量列表,选择“C:\Program Files\dotnet”,上移此条目至 “C:\Program Files (x86)\dotnet”之前,就可以找到SDK了。

设置后,在CMD下 “dotnet –info”,已经看到 .NET SDKs 条目了。

但之前创建的项目,直接打开解决方案还是不能加载,要去打开.csproj文件才能加载。或者重新新建项目。

sqlite 简单手记

delete from TableName;  //清空数据 
update sqlite_sequence SET seq = 0 where name ='TableName';//自增长ID为0
更新删除时,如何插入有单引号(')的字符串,将所有单引号替换为两个单引号

sql = sql.Replace("'","''");

保存到SQLite数据库中时自动恢复为单引号,也就是说使用双单引号即可,例如:
INSERT INTO TableName VALUES('James''s Street');
插入数据库的是: James's Street 。

sqlite数据库在搜索的时候,一些特殊的字符需要进行转义, 具体的转义如下: 
     /   ->    //
     ‘   ->    ”
     [   ->    /[
     ]   ->    /]
     %   ->    /%
     &   ->    /&
        ->    /
     (   ->    /(
     )   ->    /)

Asp.Net core Linux 监听端口的设置

在linux测试跑.net core,默认端口是5000,5001. 需要修改

尝试有以下几种方式:

1. 在项目csproj文件在linux中,编辑Properties/launchSettings.json文件中的 “applicationUrl”: “http://*:5000;http://*:5050”

2.编辑Program,直接在代码里定义

public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>()
            .UseUrls("http://*:5001/")
            .Build();

        host.Run();
    }
}

3.添加配置文件hosting.json,然后在Program中加载配置文件

public static void Main(string[] args)
{
    var config = new ConfigurationBuilder()
        .SetBasePath(Directory.GetCurrentDirectory())
        .AddJsonFile("hosting.json", true)
        .Build();

    var host = new WebHostBuilder()
        .UseKestrel(options => options.AddServerHeader = false)
        .UseConfiguration(config)
        .UseContentRoot(Directory.GetCurrentDirectory())
        .UseIISIntegration()
        .UseStartup<Startup>()
        .Build();

    host.Run();
}

4. 直接启动时增加参数,两种

在发布文件夹下直接加载dll:

dotnet WebApp1.dll --server.urls "http://*:5001;http://*:5002"

在项目文件下:

dotnet run --urls="http://*:5001/;http://*:5051/"

 

解决NuGet程序包更新安装失败的错误

管理NuGet程序包 中更新程序包,出现:

Failed to initialize the PowerShell host. If your PowerShell execution policy setting is set to AllSigned, open the Package Manager Console to initialize the host first

1. Step

Open Windows PowerShell, run as Administrator

2. Step

Setting an execution policy to RemoteSigned or Unrestricted should work. It must be changed under an administrator mode via a PowerShell console. Be aware that changes will be applied according to the bit version of the PowerShell console, so 32bit or 64 bit. So if you want to install a package in Visual Studio (32 bit version) which requires a specific policy you should change settings of the policy via PowerShell (x86).

The command in PowerShell (as administrator) to set the policy to unrestricted (as noted by @Gabriel in the comments) is:

start-job { Set-ExecutionPolicy Unrestricted } -RunAs32 | wait-job | Receive-Job

OR

NuGet is using the 32 bit console, so it wont be affected by changes to the 64 bit console. Run the following script to make sure you are configuring the 32 bit console.

start-job { Set-ExecutionPolicy RemoteSigned } -RunAs32 | wait-job | Receive-Job

3. Step

Restart Visual Studio

————————————————————-

如果所有的政策是正确的,但安装包时,仍有错误

无法初始化PowerShell主机。如果你的PowerShell执行策略设置为使用AllSigned,打开包管理器控制台首先初始化主机。

解决方案卸载  NuGet包管理器 插件,并重新安装它。

农转公/公转农 System.Globalization.ChineseLunisolarCalendar 农历转公历/公历转农历

项目中有一个生日短信提醒功能,需要每年提醒。选农历, 每年提醒, 第二年的公历是不一样的,所以每一年的都需要自己计算。

设计的要求 ,他们说因为年纪大的人是只记得农历的。。。

网上资料不少,公历转农历现成的一堆。都是用微软的System.Globalization.ChineseLunisolarCalendar类写的,
但是农历转公历的很少,也有,但都是只提到方法的调用,比如下面:
 
正确的应该是1982-10-12 。由于 并没有详细说到关键的闰月计算, 所以起初很困惑,以为计算不准确。

检查全年的月份,发现有因为有闰月的情况,有润月则应该从该闰月起月份自动加一, 如1982年润四月,或则闰五月为6月,后面的月加一处理。
方便理解自己做个对照图:

正确的方法是,要先计算当年农历生日之前的月份有没有闰月,

有了就 直接构造农历日期对象是就把农历的月+1 为9月:

只要明白闰月这一点,其实就很简单了!

///////////
//公历转农历
///////////
            DateTime date = Convert.ToDateTime(textBox1.Text);	//格式:2000-1-1
            ChineseLunisolarCalendar cc = new ChineseLunisolarCalendar();

            if (date > cc.MaxSupportedDateTime || date < cc.MinSupportedDateTime)  
                MessageBox.Show("参数日期时间不在支持的范围内,支持范围:"+cc.MinSupportedDateTime.ToShortDateString()+"到"+cc.MaxSupportedDateTime.ToShortDateString());
            
            int year = cc.GetYear(date);
            int month = cc.GetMonth(date);
            int dayOfMonth = cc.GetDayOfMonth(date);
            int leapMonth = cc.GetLeapMonth(year);
            bool isLeapMonth = cc.IsLeapMonth(year, month);
            bool isLeapYear = cc.IsLeapYear(year);

            if (isLeapMonth || isLeapYear && month >= leapMonth)
                month -= 1;

            textBox2.Text = string.Concat(year, "-", month, "-", dayOfMonth);
///////////
//农历转公历
///////////

	    ChineseLunisolarCalendar cc = new ChineseLunisolarCalendar();
            DateTime date = Convert.ToDateTime(textBox2.Text);	//格式:2000-1-1
            int MonthsInYear = cc.GetMonthsInYear(date.Year);
            int LeapMonth = cc.GetLeapMonth(date.Year, 1);
            bool isLeapMonth = cc.IsLeapMonth(date.Year, date.Month);
            bool isLeapYear = cc.IsLeapYear(date.Year);

            if (isLeapMonth)
                date = cc.ToDateTime(date.Year, date.Month - 1, date.Day, 0, 0, 0, 0);
            else if(date.Month > LeapMonth)
                date = cc.ToDateTime(date.Year, date.Month + 1, date.Day, 0, 0, 0, 0);
            else
                date = cc.ToDateTime(date.Year, date.Month, date.Day, 0, 0, 0, 0);
            
            textBox1.Text = date.ToString("yyyy-MM-dd");

这是一个WinForm做的的实例Demo: WindowsFormsApplication1

找回 Windows Server 2012 中的磁盘清理功能

公司在阿里云的新服务器,系统C盘只有40G,装了一堆程序,配置好环境,只剩下大约3个G了,看着标红的C盘容量条,很不惬意,确定要清理一下。

习惯性手工清理 + CCleaner 清理,完了没有大多少。却发现Server 2012怎么没有“磁盘清理”这个功能按钮呢?

于是搜索引擎。。。

结果是,要在“服务器管理器”中打开勾选这个功能:

安装以后在磁盘属性页就可以找到“磁盘清理”的选项了!

通过动态字符串获取变量值 & 获取变量名称

一段实例代码, 在 c#中通过 Linq 取变量的名称, 以及 将字符串转为变量名,通过字符串给变量赋值.

        string strApp = "app";
        public string app = "AAA";
        public string strTest = "TEST";
        protected void Button1_Click(object sender, EventArgs e)
        {

            //通过字符串获得变量值
            string aaa1 = this.GetType().GetField("app").GetValue(this).ToString();
            //或者
            string aaa2 = this.GetType().GetField(strApp).GetValue(this).ToString();
            //通过给变量赋值
            this.GetType().GetField("strTest").SetValue(this, "C#123");
            //新的值
            string bbb = this.GetType().GetField("strTest").GetValue(this).ToString();

            //获取变量名称
            string ccc = GetVarName(p=>this.strTest);
        }

        //获取变量名称
        public static string GetVarName(System.Linq.Expressions.Expression<Func<string, string>> exp)
      {
            return ((System.Linq.Expressions.MemberExpression)exp.Body).Member.Name;
      }