PathFormater.cs 1.9 KB

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