FileNameTemplate.cs 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Text.RegularExpressions;
  6. using System.Threading.Tasks;
  7. namespace TeamAAS_VP.Core
  8. {
  9. public class FileNameTemplate
  10. {
  11. private readonly string _template;
  12. private readonly Dictionary<string, Func<object>> _variables;
  13. public FileNameTemplate(string template)
  14. {
  15. _template = template ?? throw new ArgumentNullException(nameof(template));
  16. _variables = new Dictionary<string, Func<object>>(StringComparer.OrdinalIgnoreCase);
  17. // 注册内置变量
  18. RegisterDefaultVariables();
  19. }
  20. // 注册自定义变量
  21. public void RegisterVariable(string name, Func<object> valueProvider)
  22. {
  23. _variables[name] = valueProvider ?? throw new ArgumentNullException(nameof(valueProvider));
  24. }
  25. // 生成文件名
  26. public string Generate()
  27. {
  28. string result = _template;
  29. // 查找所有 {变量名[:格式化字符串]} 格式的占位符
  30. var matches = Regex.Matches(_template, @"\{([^}:]+)(?::([^}]+))?\}");
  31. foreach (Match match in matches)
  32. {
  33. string fullPlaceholder = match.Value;
  34. string varName = match.Groups[1].Value;
  35. string format = match.Groups[2].Success ? match.Groups[2].Value : null;
  36. if (_variables.TryGetValue(varName, out var valueProvider))
  37. {
  38. object value = valueProvider();
  39. string replacement = FormatValue(value, format);
  40. result = result.Replace(fullPlaceholder, replacement);
  41. }
  42. }
  43. // 移除文件名中不允许的字符
  44. result = SanitizeFileName(result);
  45. return result;
  46. }
  47. private string FormatValue(object value, string format)
  48. {
  49. if (value == null) return "";
  50. // 如果是日期时间类型,应用格式
  51. if (value is DateTime dateTime && !string.IsNullOrEmpty(format))
  52. {
  53. return dateTime.ToString(format);
  54. }
  55. // 如果是数值类型,应用格式
  56. if (value is IFormattable formattable && !string.IsNullOrEmpty(format))
  57. {
  58. return formattable.ToString(format, null);
  59. }
  60. return value.ToString();
  61. }
  62. private string SanitizeFileName(string fileName)
  63. {
  64. // 移除文件名中不允许的字符
  65. char[] invalidChars = System.IO.Path.GetInvalidFileNameChars();
  66. foreach (char c in invalidChars)
  67. {
  68. fileName = fileName.Replace(c.ToString(), "");
  69. }
  70. return fileName;
  71. }
  72. private void RegisterDefaultVariables()
  73. {
  74. // 日期时间变量
  75. RegisterVariable("Now", () => DateTime.Now);
  76. RegisterVariable("Today", () => DateTime.Today);
  77. RegisterVariable("UtcNow", () => DateTime.UtcNow);
  78. // 可以在这里添加更多内置变量
  79. }
  80. }
  81. }