| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Text.RegularExpressions;
- using System.Threading.Tasks;
- namespace TeamAAS_VP.Core
- {
- public class FileNameTemplate
- {
- private readonly string _template;
- private readonly Dictionary<string, Func<object>> _variables;
- public FileNameTemplate(string template)
- {
- _template = template ?? throw new ArgumentNullException(nameof(template));
- _variables = new Dictionary<string, Func<object>>(StringComparer.OrdinalIgnoreCase);
- // 注册内置变量
- RegisterDefaultVariables();
- }
- // 注册自定义变量
- public void RegisterVariable(string name, Func<object> valueProvider)
- {
- _variables[name] = valueProvider ?? throw new ArgumentNullException(nameof(valueProvider));
- }
- // 生成文件名
- public string Generate()
- {
- string result = _template;
- // 查找所有 {变量名[:格式化字符串]} 格式的占位符
- var matches = Regex.Matches(_template, @"\{([^}:]+)(?::([^}]+))?\}");
- foreach (Match match in matches)
- {
- string fullPlaceholder = match.Value;
- string varName = match.Groups[1].Value;
- string format = match.Groups[2].Success ? match.Groups[2].Value : null;
- if (_variables.TryGetValue(varName, out var valueProvider))
- {
- object value = valueProvider();
- string replacement = FormatValue(value, format);
- result = result.Replace(fullPlaceholder, replacement);
- }
- }
- // 移除文件名中不允许的字符
- result = SanitizeFileName(result);
- return result;
- }
- private string FormatValue(object value, string format)
- {
- if (value == null) return "";
- // 如果是日期时间类型,应用格式
- if (value is DateTime dateTime && !string.IsNullOrEmpty(format))
- {
- return dateTime.ToString(format);
- }
- // 如果是数值类型,应用格式
- if (value is IFormattable formattable && !string.IsNullOrEmpty(format))
- {
- return formattable.ToString(format, null);
- }
- return value.ToString();
- }
- private string SanitizeFileName(string fileName)
- {
- // 移除文件名中不允许的字符
- char[] invalidChars = System.IO.Path.GetInvalidFileNameChars();
- foreach (char c in invalidChars)
- {
- fileName = fileName.Replace(c.ToString(), "");
- }
- return fileName;
- }
- private void RegisterDefaultVariables()
- {
- // 日期时间变量
- RegisterVariable("Now", () => DateTime.Now);
- RegisterVariable("Today", () => DateTime.Today);
- RegisterVariable("Now", () => DateTime.Now);
- // 可以在这里添加更多内置变量
- }
- }
- }
|