如何在 C# 中创建包含日期/时间的文件名
在数据记录中,你经常需要在开始记录数据时创建新的日志文件。
在大多数情况下,在日志文件中包含当前日期和时间很方便。以下是在 C# 中不使用外部库的方法:
create-filename.cs
string filename = String.Format("Temperature logging {0}.csv",
DateTime.UtcNow.ToString("yyyy-MM-dd HH-mm-ss"));这将创建类似这样的文件名
example-filenames.txt
Temperature log 2020-06-17 22-37-41.csv
Temperature log 2019-12-31 00-15-55.csv注意如果你使用其他日期/时间格式,你需要避免文件名中不能出现的特殊字符。Linux 上文件名正确的规则比 Windows 上简单得多,但由于你应该与两种操作系统兼容,你应该始终检查 Windows 规则。
Windows 文件名禁止以下字符:
forbidden-windows-filename-chars.txt
<>:"/\|?*我们上面使用的日期时间格式 yyyy-MM-dd HH-mm-ss 是专门设计的,以避免在类似 ISO-8601 的日期/时间格式(如 2020-04-02 11:45:33)中使用冒号,因为冒号在 Windows 文件名中是非法的。yyyy-MM-dd HH-mm-ss 只包含空格和减号(-)字符,以避免现在和将来的任何问题。
Check out similar posts by category:
C#
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow