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.

377 lines
13 KiB

5 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Web;
  5. using System.Text.RegularExpressions;
  6. using System.Linq;
  7. using SiteServer.Utils.Enumerations;
  8. namespace SiteServer.Utils
  9. {
  10. public static class PathUtils
  11. {
  12. public const char SeparatorChar = '\\';
  13. public static readonly char[] InvalidPathChars = Path.GetInvalidPathChars();
  14. public static bool IsExtension(string ext, params string[] extensions)
  15. {
  16. return extensions.Any(extension => StringUtils.EqualsIgnoreCase(ext, extension));
  17. }
  18. public static string GetLibraryFileName(string filePath)
  19. {
  20. return $"{StringUtils.GetShortGuid(false)}{GetExtension(filePath)}";
  21. }
  22. public static string GetLibraryVirtualPath(EUploadType uploadType, string fileName)
  23. {
  24. var uploadDirectoryName = string.Empty;
  25. if (uploadType == EUploadType.Image)
  26. {
  27. uploadDirectoryName = "images";
  28. }
  29. else if (uploadType == EUploadType.Video)
  30. {
  31. uploadDirectoryName = "videos";
  32. }
  33. else if (uploadType == EUploadType.File)
  34. {
  35. uploadDirectoryName = "files";
  36. }
  37. else if (uploadType == EUploadType.Special)
  38. {
  39. uploadDirectoryName = "specials";
  40. }
  41. return $"/{DirectoryUtils.SiteFiles.DirectoryName}/{DirectoryUtils.SiteFiles.Library}/{uploadDirectoryName}/{DateTime.Now.Year}/{DateTime.Now.Month}/{fileName}";
  42. }
  43. //将编辑器中图片上传至本机
  44. public static string SaveLibraryImage(string content)
  45. {
  46. var originalImageSrcs = RegexUtils.GetOriginalImageSrcs(content);
  47. foreach (var originalImageSrc in originalImageSrcs)
  48. {
  49. if (!PageUtils.IsProtocolUrl(originalImageSrc) ||
  50. StringUtils.StartsWithIgnoreCase(originalImageSrc, PageUtils.ApplicationPath))
  51. continue;
  52. var fileExtName = PageUtils.GetExtensionFromUrl(originalImageSrc);
  53. if (!EFileSystemTypeUtils.IsImageOrFlashOrPlayer(fileExtName)) continue;
  54. var fileName = GetLibraryFileName(originalImageSrc);
  55. var virtualPath = GetLibraryVirtualPath(EUploadType.Image, fileName);
  56. var filePath = Combine(WebConfigUtils.PhysicalApplicationPath, virtualPath);
  57. try
  58. {
  59. if (!FileUtils.IsFileExists(filePath))
  60. {
  61. WebClientUtils.SaveRemoteFileToLocal(originalImageSrc, filePath);
  62. }
  63. content = content.Replace(originalImageSrc, virtualPath);
  64. }
  65. catch
  66. {
  67. // ignored
  68. }
  69. }
  70. return content;
  71. }
  72. public static string Combine(params string[] paths)
  73. {
  74. var retVal = string.Empty;
  75. if (paths != null && paths.Length > 0)
  76. {
  77. retVal = paths[0]?.Replace(PageUtils.SeparatorChar, SeparatorChar).TrimEnd(SeparatorChar) ?? string.Empty;
  78. for (var i = 1; i < paths.Length; i++)
  79. {
  80. var path = paths[i] != null ? paths[i].Replace(PageUtils.SeparatorChar, SeparatorChar).Trim(SeparatorChar) : string.Empty;
  81. retVal = Path.Combine(retVal, path);
  82. }
  83. }
  84. return retVal;
  85. }
  86. /// <summary>
  87. /// 根据路径扩展名判断是否为文件夹路径
  88. /// </summary>
  89. /// <param name="path"></param>
  90. /// <returns></returns>
  91. public static bool IsDirectoryPath(string path)
  92. {
  93. var retVal = false;
  94. if (!string.IsNullOrEmpty(path))
  95. {
  96. var ext = Path.GetExtension(path);
  97. if (string.IsNullOrEmpty(ext)) //path为文件路径
  98. {
  99. retVal = true;
  100. }
  101. }
  102. return retVal;
  103. }
  104. public static bool IsFilePath(string val)
  105. {
  106. try
  107. {
  108. return FileUtils.IsFileExists(val);
  109. }
  110. catch
  111. {
  112. return false;
  113. }
  114. }
  115. public static string GetExtension(string path)
  116. {
  117. var retVal = string.Empty;
  118. if (!string.IsNullOrEmpty(path))
  119. {
  120. path = PageUtils.RemoveQueryString(path);
  121. path = path.Trim('/', '\\').Trim();
  122. try
  123. {
  124. retVal = Path.GetExtension(path);
  125. }
  126. catch
  127. {
  128. // ignored
  129. }
  130. }
  131. return retVal;
  132. }
  133. public static string RemoveExtension(string fileName)
  134. {
  135. var retVal = string.Empty;
  136. if (!string.IsNullOrEmpty(fileName))
  137. {
  138. var index = fileName.LastIndexOf('.');
  139. retVal = index != -1 ? fileName.Substring(0, index) : fileName;
  140. }
  141. return retVal;
  142. }
  143. public static string RemoveParentPath(string path)
  144. {
  145. var retVal = string.Empty;
  146. if (!string.IsNullOrEmpty(path))
  147. {
  148. retVal = path.Replace("../", string.Empty);
  149. retVal = retVal.Replace("./", string.Empty);
  150. }
  151. return retVal;
  152. }
  153. public static string GetFileName(string filePath)
  154. {
  155. return Path.GetFileName(filePath);
  156. }
  157. private static char[] GetInvalidChars()
  158. {
  159. return Path.GetInvalidFileNameChars().Concat(Path.GetInvalidPathChars()).Concat(new[] {' ', ';'}).ToArray();
  160. }
  161. public static string GetSafeFilename(string filename)
  162. {
  163. if (string.IsNullOrEmpty(filename)) return StringUtils.GetShortGuid().ToLower();
  164. return string.Join("_", filename.Split(GetInvalidChars()));
  165. }
  166. public static string GetFileNameWithoutExtension(string filePath)
  167. {
  168. return Path.GetFileNameWithoutExtension(filePath);
  169. }
  170. public static string GetDirectoryName(string path, bool isFile)
  171. {
  172. if (string.IsNullOrWhiteSpace(path)) return string.Empty;
  173. if (isFile)
  174. {
  175. path = Path.GetDirectoryName(path);
  176. }
  177. if (!string.IsNullOrEmpty(path))
  178. {
  179. var directoryInfo = new DirectoryInfo(path);
  180. return directoryInfo.Name;
  181. }
  182. return string.Empty;
  183. }
  184. public static string GetPathDifference(string rootPath, string path)
  185. {
  186. if (!string.IsNullOrEmpty(path) && StringUtils.StartsWithIgnoreCase(path, rootPath))
  187. {
  188. var retVal = path.Substring(rootPath.Length, path.Length - rootPath.Length);
  189. return retVal.Trim('/', '\\');
  190. }
  191. return string.Empty;
  192. }
  193. public static string GetCurrentPagePath()
  194. {
  195. if (HttpContext.Current != null)
  196. {
  197. return HttpContext.Current.Request.PhysicalPath;
  198. }
  199. return string.Empty;
  200. }
  201. public static string GetSiteFilesPath(params string[] paths)
  202. {
  203. return MapPath(Combine("~/" + DirectoryUtils.SiteFiles.DirectoryName, Combine(paths)));
  204. }
  205. public static string GetBinDirectoryPath(string relatedPath)
  206. {
  207. relatedPath = RemoveParentPath(relatedPath);
  208. return Combine(WebConfigUtils.PhysicalApplicationPath, DirectoryUtils.Bin.DirectoryName, relatedPath);
  209. }
  210. public static string GetAdminDirectoryPath(string relatedPath)
  211. {
  212. relatedPath = RemoveParentPath(relatedPath);
  213. return Combine(WebConfigUtils.PhysicalApplicationPath, WebConfigUtils.AdminDirectory, relatedPath);
  214. }
  215. public static string GetHomeDirectoryPath(string relatedPath)
  216. {
  217. relatedPath = RemoveParentPath(relatedPath);
  218. return Combine(WebConfigUtils.PhysicalApplicationPath, WebConfigUtils.HomeDirectory, relatedPath);
  219. }
  220. public static string PluginsPath => GetSiteFilesPath(DirectoryUtils.SiteFiles.Plugins);
  221. public static string GetPluginPath(string pluginId, params string[] paths)
  222. {
  223. return GetSiteFilesPath(DirectoryUtils.SiteFiles.Plugins, pluginId, Combine(paths));
  224. }
  225. public static string GetPluginNuspecPath(string pluginId)
  226. {
  227. return GetPluginPath(pluginId, pluginId + ".nuspec");
  228. }
  229. public static string GetPluginDllDirectoryPath(string pluginId)
  230. {
  231. var fileName = pluginId + ".dll";
  232. var filePaths = Directory.GetFiles(GetPluginPath(pluginId, "Bin"), fileName, SearchOption.AllDirectories);
  233. var dict = new Dictionary<DateTime, string>();
  234. foreach (var filePath in filePaths)
  235. {
  236. var lastModifiedDate = File.GetLastWriteTime(filePath);
  237. dict[lastModifiedDate] = filePath;
  238. }
  239. if (dict.Count > 0)
  240. {
  241. var filePath = dict.OrderByDescending(x => x.Key).First().Value;
  242. return Path.GetDirectoryName(filePath);
  243. }
  244. //if (FileUtils.IsFileExists(GetPluginPath(pluginId, "Bin", fileName)))
  245. //{
  246. // return GetPluginPath(pluginId, "Bin");
  247. //}
  248. //if (FileUtils.IsFileExists(GetPluginPath(pluginId, "Bin", "Debug", "net4.6.1", fileName)))
  249. //{
  250. // return GetPluginPath(pluginId, "Bin", "Debug");
  251. //}
  252. //if (FileUtils.IsFileExists(GetPluginPath(pluginId, "Bin", "Debug", "net4.6.1", fileName)))
  253. //{
  254. // return GetPluginPath(pluginId, "Bin", "Debug");
  255. //}
  256. //if (FileUtils.IsFileExists(GetPluginPath(pluginId, "Bin", "Debug", fileName)))
  257. //{
  258. // return GetPluginPath(pluginId, "Bin", "Debug");
  259. //}
  260. //if (FileUtils.IsFileExists(GetPluginPath(pluginId, "Bin", "Release", fileName)))
  261. //{
  262. // return GetPluginPath(pluginId, "Bin", "Release");
  263. //}
  264. return string.Empty;
  265. }
  266. public static string GetPackagesPath(params string[] paths)
  267. {
  268. var packagesPath = GetSiteFilesPath(DirectoryUtils.SiteFiles.Packages, Combine(paths));
  269. DirectoryUtils.CreateDirectoryIfNotExists(packagesPath);
  270. return packagesPath;
  271. }
  272. public static string RemovePathInvalidChar(string filePath)
  273. {
  274. if (string.IsNullOrEmpty(filePath))
  275. return filePath;
  276. var invalidChars = new string(Path.GetInvalidPathChars());
  277. string invalidReStr = $"[{Regex.Escape(invalidChars)}]";
  278. return Regex.Replace(filePath, invalidReStr, "");
  279. }
  280. public static string MapPath(string virtualPath)
  281. {
  282. virtualPath = RemovePathInvalidChar(virtualPath);
  283. string retVal;
  284. if (!string.IsNullOrEmpty(virtualPath))
  285. {
  286. if (virtualPath.StartsWith("~"))
  287. {
  288. virtualPath = virtualPath.Substring(1);
  289. }
  290. virtualPath = PageUtils.Combine("~", virtualPath);
  291. }
  292. else
  293. {
  294. virtualPath = "~/";
  295. }
  296. if (HttpContext.Current != null)
  297. {
  298. retVal = HttpContext.Current.Server.MapPath(virtualPath);
  299. }
  300. else
  301. {
  302. var rootPath = WebConfigUtils.PhysicalApplicationPath;
  303. virtualPath = !string.IsNullOrEmpty(virtualPath) ? virtualPath.Substring(2) : string.Empty;
  304. retVal = Combine(rootPath, virtualPath);
  305. }
  306. if (retVal == null) retVal = string.Empty;
  307. return retVal.Replace("/", "\\");
  308. }
  309. public static bool IsFileExtenstionAllowed(string sAllowedExt, string sExt)
  310. {
  311. if (sExt != null && sExt.StartsWith("."))
  312. {
  313. sExt = sExt.Substring(1, sExt.Length - 1);
  314. }
  315. sAllowedExt = sAllowedExt.Replace("|", ",");
  316. var aExt = sAllowedExt.Split(',');
  317. return aExt.Any(t => StringUtils.EqualsIgnoreCase(sExt, t));
  318. }
  319. public static string GetTemporaryFilesPath(string relatedPath)
  320. {
  321. return Combine(WebConfigUtils.PhysicalApplicationPath, DirectoryUtils.SiteFiles.DirectoryName, DirectoryUtils.SiteFiles.TemporaryFiles, relatedPath);
  322. }
  323. public static string GetMenusPath(params string[] paths)
  324. {
  325. return Combine(SiteServerAssets.GetPath("menus"), Combine(paths));
  326. }
  327. public static string PhysicalSiteServerPath => Combine(WebConfigUtils.PhysicalApplicationPath, WebConfigUtils.AdminDirectory);
  328. public static string PhysicalSiteFilesPath => Combine(WebConfigUtils.PhysicalApplicationPath, DirectoryUtils.SiteFiles.DirectoryName);
  329. }
  330. }