PageRenderTime 56ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 0ms

/Naming/FileNaming.cs

http://cachecopy.codeplex.com
C# | 250 lines | 123 code | 46 blank | 81 comment | 13 complexity | 2455faceb9d7ff0f1c4af7bfcf234b9f MD5 | raw file
Possible License(s): GPL-2.0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using FileTypeDetective;
  5. namespace cacheCopy
  6. {
  7. public class FileNaming
  8. {
  9. /// <summary>
  10. /// Generates the name of the file taking into account all the settings provided by user in GUI:
  11. /// * pattern
  12. /// * Overwrite existing files or not
  13. /// * adds extension to the file if not already there
  14. /// </summary>
  15. /// <param name="file">The file.</param>
  16. /// <param name="pattern">The pattern.</param>
  17. /// <param name="allowOverwrite">if set to <c>true</c> [allow overwrite].</param>
  18. /// <param name="targetPath">The target path.</param>
  19. /// <param name="Number">The number.</param>
  20. /// <returns></returns>
  21. public static string GenerateFileName(FileInfo file, String pattern, bool allowOverwrite, string targetPath, string Number = "" )
  22. {
  23. String name = file.Name;
  24. // if pattern is set, process the pattern
  25. if (pattern != null && pattern != String.Empty)
  26. {
  27. name = HandlePatternName(file, pattern, Number);
  28. }
  29. // check for file extension in the pattern
  30. // if the extension exists in pattern, do nothing
  31. if (!NameIncludesCorrectExtension(name))
  32. {
  33. // if there is no extension, take it from fileType
  34. // add extension to the end of the fileName
  35. name += '.' + file.GetFileType().extension;
  36. }
  37. // then check if the filename with this name already exists
  38. if (!allowOverwrite)
  39. {
  40. //create new name - add (1) at the name end
  41. name = CorrectNameIfFileExits(file, name, targetPath);
  42. }
  43. return Path.Combine(targetPath, name);
  44. }
  45. /// <summary>
  46. /// Replace placeholders in pattern for the information
  47. /// from file and other data
  48. /// </summary>
  49. /// <param name="file">The file.</param>
  50. /// <param name="pattern">The pattern.</param>
  51. /// <returns></returns>
  52. private static string HandlePatternName(FileInfo file, string pattern, string Number)
  53. {
  54. DateTime FileCreatedTime = file.CreationTime;
  55. return ReplacePlaceholders(pattern, FileCreatedTime, Number);
  56. }
  57. /// <summary>
  58. /// Check if given file names already includes the correct extension.
  59. /// Basically we need to check if the filename ends with one of the known extension
  60. /// </summary>
  61. /// <param name="name">The name.</param>
  62. /// <returns>true if filename already has allowed extension at the end</returns>
  63. private static bool NameIncludesCorrectExtension(string name)
  64. {
  65. List<string> allowedExtension = new List<string> {
  66. ".jpg",
  67. ".jpeg",
  68. ".gif",
  69. ".png"
  70. };
  71. foreach (string ext in allowedExtension)
  72. {
  73. if (name.EndsWith(ext))
  74. return true;
  75. }
  76. return false;
  77. }
  78. /// <summary>
  79. /// Check if the file with this name and path already exists and
  80. /// add (1) or (2), etc. at the end of the name, before the extension
  81. /// </summary>
  82. /// <param name="file">The file.</param>
  83. /// <param name="name">The name.</param>
  84. private static string CorrectNameIfFileExits(FileInfo file, string name, string targetPath)
  85. {
  86. string newFullName = Path.Combine(targetPath, name);
  87. int i = 0;
  88. while (File.Exists(newFullName)) // check if file exists
  89. {
  90. i++; // if file exists, add counter
  91. string nameNoExtension = Path.GetFileNameWithoutExtension(newFullName);
  92. string extension = Path.GetExtension(newFullName);
  93. // and add the number to the file name
  94. newFullName = Path.Combine(targetPath, nameNoExtension + "(" + i.ToString() + ")" + extension);
  95. }
  96. return newFullName;
  97. }
  98. /// <summary>
  99. /// Build a dictionary of replacement strings
  100. /// </summary>
  101. /// <param name="FileCreatedTime">The file created time.</param>
  102. /// <param name="Number">The string with current file number - with zeros as padding.</param>
  103. /// <returns>dictionary with strings</returns>
  104. private static Dictionary<string, string> GetReplacementPattern(DateTime FileCreatedTime, string Number)
  105. {
  106. // for more date string formats go here:
  107. //http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
  108. Dictionary<string, string> replacements = new Dictionary<string, string>()
  109. {
  110. //current computer time
  111. {"*yyyy*", DateTime.Now.ToString("yyyy")}, // 1999
  112. {"*yy*", DateTime.Now.ToString("yy")}, // 99
  113. {"*MM*", DateTime.Now.ToString("MM")}, // 02 (for February)
  114. {"*MMM*", DateTime.Now.ToString("MMM")}, // Feb (for February)
  115. {"*dd*", DateTime.Now.ToString("dd")}, // 05 for fifth
  116. {"*HH*", DateTime.Now.ToString("HH")}, // 07 - hours
  117. {"*mm*", DateTime.Now.ToString("mm")}, // minutes
  118. {"*ss*", DateTime.Now.ToString("ss")}, // seconds
  119. {"*ffff*", DateTime.Now.ToString("ffff")}, // The hundredths of a second
  120. {"*fffffff*", DateTime.Now.ToString("fffffff")}, //The ten millionths of a second
  121. //Timestamp for file creation time
  122. {"*CFyyyy*", FileCreatedTime.ToString("yyyy")},
  123. {"*CFyy*", FileCreatedTime.ToString("yy")},
  124. {"*CFMM*", FileCreatedTime.ToString("MM")},
  125. {"*CFMMM*", FileCreatedTime.ToString("MMM")},
  126. {"*CFdd*", FileCreatedTime.ToString("dd")},
  127. {"*CFHH*", FileCreatedTime.ToString("HH")},
  128. {"*CFmm*", FileCreatedTime.ToString("mm")},
  129. {"*CFss*", FileCreatedTime.ToString("ss")},
  130. {"*CFff*", FileCreatedTime.ToString("ff")},
  131. // random string of letters/digits
  132. {"*RAND3*", Util.GenerateRandomString(3)},
  133. {"*RAND4*", Util.GenerateRandomString(4)},
  134. {"*RAND5*", Util.GenerateRandomString(5)},
  135. {"*RAND6*", Util.GenerateRandomString(6)},
  136. // number of the file in the queue with padding
  137. {"*NUM*", Number}
  138. };
  139. return replacements;
  140. }
  141. /// <summary>
  142. /// Determines whether the provided pattern is valid in terms of the file naming conventions,
  143. /// allowed symbols and all the possible replacements.
  144. /// </summary>
  145. /// <param name="pattern">The string with pattern.</param>
  146. /// <returns>
  147. /// <c>true</c> if pattern is valid; otherwise, <c>false</c>.
  148. /// </returns>
  149. public static bool isPatternValid(string pattern)
  150. {
  151. // avoid assigning to the parameter
  152. String name = ReplacePlaceholders(pattern, DateTime.Now, "");
  153. return Util.IsValidFileName(name);
  154. }
  155. /// <summary>
  156. /// Replaces the placeholders in pattern to a values
  157. /// </summary>
  158. /// <param name="pattern">The pattern.</param>
  159. /// <param name="FileCreatedTime">File creation time.</param>
  160. /// <param name="Number">String with number of the file in the process line.</param>
  161. /// <returns>string with replaced placeholders</returns>
  162. private static string ReplacePlaceholders(String pattern, DateTime FileCreatedTime, string Number)
  163. {
  164. // avoid assigning to the parameter
  165. String name = pattern;
  166. // get all the possible replacements
  167. Dictionary<string, string> replacements = GetReplacementPattern(FileCreatedTime, Number);
  168. // replace every wildcard with value
  169. foreach (var pair in replacements)
  170. {
  171. name = name.Replace(pair.Key, pair.Value);
  172. }
  173. return name;
  174. }
  175. /// <summary>
  176. /// Produces sample file name based on the pattern provided
  177. /// by user - just for an example, to see the resulting file name.
  178. /// </summary>
  179. /// <param name="pattern">The pattern.</param>
  180. /// <returns>Pattern with replaced placeholders</returns>
  181. public static string GenerateSampleFileName(string pattern)
  182. {
  183. String result = "";
  184. // if pattern is set, process the pattern
  185. if (pattern != null && pattern != String.Empty)
  186. {
  187. result = ReplacePlaceholders(pattern, DateTime.Now, "001");
  188. }
  189. else
  190. {
  191. return "";
  192. }
  193. // check for file extension in the pattern
  194. // if the extension exists in pattern, do nothing
  195. if (!NameIncludesCorrectExtension(result))
  196. {
  197. // if there is no extension, take it from fileType
  198. // add extension to the end of the fileName
  199. result += ".jpg";
  200. }
  201. return result;
  202. }
  203. }
  204. }