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.

48 lines
2.0 KiB

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