You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
1.8 KiB

2 years ago
  1. using System;
  2. using System.IO;
  3. using System.Text.RegularExpressions;
  4. /// <summary>
  5. /// PathFormater 的摘要说明
  6. /// </summary>
  7. public static class PathFormatter
  8. {
  9. public static string Format(string originFileName, string pathFormat)
  10. {
  11. if (String.IsNullOrWhiteSpace(pathFormat))
  12. {
  13. pathFormat = "{filename}{rand:6}";
  14. }
  15. var invalidPattern = new Regex(@"[\\\/\:\*\?\042\<\>\|]");
  16. originFileName = invalidPattern.Replace(originFileName, "");
  17. var extension = Path.GetExtension(originFileName);
  18. var filename = Path.GetFileNameWithoutExtension(originFileName);
  19. pathFormat = pathFormat.Replace("{filename}", filename);
  20. pathFormat = new Regex(@"\{rand(\:?)(\d+)\}", RegexOptions.Compiled).Replace(pathFormat, new MatchEvaluator(delegate (Match match)
  21. {
  22. var digit = 6;
  23. if (match.Groups.Count > 2)
  24. {
  25. digit = Convert.ToInt32(match.Groups[2].Value);
  26. }
  27. var rand = new Random();
  28. return rand.Next((int)Math.Pow(10, digit), (int)Math.Pow(10, digit + 1)).ToString();
  29. }));
  30. pathFormat = pathFormat.Replace("{time}", DateTime.Now.Ticks.ToString());
  31. pathFormat = pathFormat.Replace("{yyyy}", DateTime.Now.Year.ToString());
  32. pathFormat = pathFormat.Replace("{yy}", (DateTime.Now.Year % 100).ToString("D2"));
  33. pathFormat = pathFormat.Replace("{mm}", DateTime.Now.Month.ToString("D2"));
  34. pathFormat = pathFormat.Replace("{dd}", DateTime.Now.Day.ToString("D2"));
  35. pathFormat = pathFormat.Replace("{hh}", DateTime.Now.Hour.ToString("D2"));
  36. pathFormat = pathFormat.Replace("{ii}", DateTime.Now.Minute.ToString("D2"));
  37. pathFormat = pathFormat.Replace("{ss}", DateTime.Now.Second.ToString("D2"));
  38. return pathFormat + extension;
  39. }
  40. }