PageRenderTime 48ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/tool/FileUtility.cs

https://github.com/moscrif/ide
C# | 505 lines | 323 code | 102 blank | 80 comment | 86 complexity | d67cd17d0b5cdb1baf8d5d400f234c06 MD5 | raw file
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using System.Text.RegularExpressions;
  5. using System.Collections;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using Moscrif.IDE.Iface.Entities;
  9. namespace Moscrif.IDE.Tool
  10. {
  11. public static class FileUtility
  12. {
  13. internal readonly static char[] separators = { Path.DirectorySeparatorChar, Path.VolumeSeparatorChar };
  14. /// <summary>
  15. /// Removes trailing '.' character from a path.
  16. /// </summary>
  17. /// <param name="path">The path from which to remove the trailing
  18. /// '.' character.</param>
  19. /// <returns>A path without any trailing '.'.</returns>
  20. public static string TrimTrailingDotCharacter(string path)
  21. {
  22. if (path.Length > 0 && path [path.Length - 1] == '.')
  23. return path.Remove(path.Length - 1, 1);
  24. else
  25. return path;
  26. }
  27. /// <summary>
  28. /// Removes trailing '\' or '/' from a path.
  29. /// </summary>
  30. /// <param name="path">The path from which to remove the trailing
  31. /// directory separator.</param>
  32. /// <returns>A path without any trailing directory separator.</returns>
  33. public static string TrimTrailingDirectorySeparator(string path)
  34. {
  35. if (path.Length == 0)
  36. return path;
  37. if ((path [path.Length - 1] == separators [0]) || (path [path.Length - 1] == separators [1])){
  38. path = path.Remove(path.Length - 1, 1);
  39. }
  40. return path;
  41. }
  42. /// <summary>
  43. /// Removes starting '\' or '/' from a path.
  44. /// </summary>
  45. /// <param name="path">The path from which to remove the starting
  46. /// directory separator.</param>
  47. /// <returns>A path without any starting directory separator.</returns>
  48. public static string TrimStartingDirectorySeparator(string path) {
  49. if (path.Length == 0)
  50. return path;
  51. if ((path [0] == separators [0]) || (path [0] == separators [1])) {
  52. path = path.Remove(0, 1);
  53. TrimStartingDirectorySeparator(path);
  54. }
  55. return path;
  56. }
  57. /// <summary>
  58. /// Removes starting '.' character from a path.
  59. /// </summary>
  60. /// <param name="path">The path from which to remove the starting
  61. /// '.' character.</param>
  62. /// <returns>A path without any starting '.'.</returns>
  63. public static string TrimStartingDotCharacter(string path)
  64. {
  65. if (path.Length > 0 && path [0] == '.') {
  66. path = path.Remove(0, 1);
  67. TrimStartingDotCharacter(path);
  68. //return path;
  69. }
  70. return path;
  71. }
  72. /// <summary>
  73. /// Converts a given absolute path and a given base path to a path that leads
  74. /// from the base path to the absoulte path. (as a relative path)
  75. /// </summary>
  76. /// <remarks>
  77. /// <para>The returned relative path will be of the form:</para>
  78. /// <para><code>
  79. /// .\Test
  80. /// .\Test\Test.prjx
  81. /// .\Test.prjx
  82. /// .\
  83. /// ..\bin
  84. /// ..\..\bin\debug
  85. /// </code>
  86. /// </para>
  87. /// </remarks>
  88. public static string AbsoluteToRelativePath(string baseDirectoryPath, string absPath)
  89. {
  90. //absPath = absPath.Replace('/',Path.DirectorySeparatorChar);
  91. //absPath = absPath.Replace('\\',Path.DirectorySeparatorChar);
  92. // Remove trailing '.'
  93. baseDirectoryPath = TrimTrailingDotCharacter(baseDirectoryPath);
  94. // Remove trailing directory separators.
  95. baseDirectoryPath = TrimTrailingDirectorySeparator(baseDirectoryPath);
  96. absPath = TrimTrailingDirectorySeparator(absPath);
  97. // Remove ".\" occurrences.
  98. absPath = absPath.Replace(String.Concat(".", separators [0]), String.Empty);
  99. absPath = absPath.Replace(String.Concat(".", separators [1]), String.Empty);
  100. string[] bPath = baseDirectoryPath.Split(separators);
  101. string[] aPath = absPath.Split(separators);
  102. int indx = 0;
  103. for (; indx < Math.Min(bPath.Length, aPath.Length); ++indx)
  104. //if(!bPath[indx].Equals(aPath[indx]))
  105. if (String.Compare(bPath [indx], aPath [indx], true) != 0)
  106. break;
  107. if (indx == 0)
  108. return absPath;
  109. StringBuilder erg = new StringBuilder();
  110. if (indx == bPath.Length) {
  111. erg.Append('.');
  112. erg.Append(Path.DirectorySeparatorChar);
  113. } else
  114. for (int i = indx; i < bPath.Length; ++i) {
  115. erg.Append("..");
  116. erg.Append(Path.DirectorySeparatorChar);
  117. }
  118. erg.Append(String.Join(Path.DirectorySeparatorChar.ToString(), aPath, indx, aPath.Length - indx));
  119. return erg.ToString();
  120. }
  121. /// <summary>
  122. /// Converts a given relative path and a given base path to a path that leads
  123. /// to the relative path absoulte.
  124. /// </summary>
  125. public static string RelativeToAbsolutePath(string baseDirectoryPath, string relPath)
  126. {
  127. relPath = relPath.Replace('/', Path.DirectorySeparatorChar);
  128. relPath = relPath.Replace('\\', Path.DirectorySeparatorChar);
  129. if (separators [0] != separators [1] && relPath.IndexOf(separators [1]) != -1)
  130. return relPath;
  131. string[] bPath = baseDirectoryPath.Split(separators [0]);
  132. string[] rPath = relPath.Split(separators [0]);
  133. int indx = 0;
  134. for (; indx < rPath.Length; ++indx)
  135. if (!rPath[indx].Equals("..")) {
  136. break;
  137. }
  138. if (indx == 0)
  139. return baseDirectoryPath + separators[0] + String.Join(Path.DirectorySeparatorChar.ToString(), rPath, 1, rPath.Length - 1);
  140. string erg = String.Join(Path.DirectorySeparatorChar.ToString(), bPath, 0, Math.Max(0, bPath.Length - indx));
  141. erg += separators [0] + String.Join(Path.DirectorySeparatorChar.ToString(), rPath, indx, rPath.Length - indx);
  142. return erg;
  143. }
  144. public static string GetSystemPath(string path)
  145. {
  146. if(String.IsNullOrEmpty(path))
  147. return path;
  148. string sysPath = path.Replace('/', Path.DirectorySeparatorChar);
  149. sysPath = sysPath.Replace('\\', Path.DirectorySeparatorChar);
  150. return sysPath;
  151. }
  152. public static MatchCollection FindInFileRegEx(string filePath, string expresion)
  153. {
  154. if (!System.IO.File.Exists(filePath))
  155. return null;
  156. FileAttributes fa = File.GetAttributes(filePath);
  157. if ((fa & FileAttributes.System) == FileAttributes.System) {
  158. return null;
  159. }
  160. if ((fa & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) {
  161. return null;
  162. }
  163. try{
  164. StreamReader reader = new StreamReader(filePath);
  165. string content = reader.ReadToEnd();
  166. reader.Close();
  167. Regex regexBar = new Regex(expresion, RegexOptions.IgnorePatternWhitespace | RegexOptions.Compiled | RegexOptions.CultureInvariant);
  168. MatchCollection mcAll =regexBar.Matches(content);//Regex.Matches(content, expresion);
  169. return mcAll;
  170. }catch {
  171. return null;
  172. }
  173. }
  174. public static List<FindResult> FindInFile(string filePath, string expresion, bool caseSensitve, bool wholeWorlds, string replaceExpresion)
  175. {
  176. if (!System.IO.File.Exists(filePath))
  177. return null;
  178. FileAttributes fa = File.GetAttributes(filePath);
  179. if ((fa & FileAttributes.System) == FileAttributes.System) {
  180. return null;
  181. }
  182. if ((fa & FileAttributes.ReadOnly) == FileAttributes.ReadOnly) {
  183. return null;
  184. }
  185. List<FindResult> result = new List<FindResult>();
  186. StreamReader reader = new StreamReader(filePath);
  187. bool isChanged = false;
  188. StringBuilder sb = new StringBuilder();
  189. int indx = 0;
  190. do {
  191. string line = reader.ReadLine();
  192. if(String.IsNullOrEmpty(line)){
  193. indx++;
  194. continue;
  195. }
  196. var comparison = caseSensitve ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
  197. int idx = 0;
  198. int delta = 0;
  199. while ((idx = line.IndexOf (expresion, idx, line.Length - idx, comparison)) >= 0) {
  200. if (!wholeWorlds || IsWholeWordAt(line, idx, expresion.Length))
  201. if (replaceExpresion != null) {
  202. Replace(ref line, idx + delta, expresion.Length, replaceExpresion);
  203. isChanged = true;
  204. //yield return new SearchResult (provider, idx + delta, replacePattern.Length);
  205. result.Add(new FindResult((object)indx, (object)line));
  206. delta += replaceExpresion.Length - expresion.Length;
  207. } else
  208. result.Add(new FindResult( (object)(indx+1),(object)line));
  209. //yield return new SearchResult (provider, idx, pattern.Length);
  210. idx += expresion.Length;
  211. }
  212. sb.AppendLine(line);
  213. /* if(caseSensitve && !wholeWorlds){
  214. if(line.Contains(expresion) )
  215. result.Add(indx,line);
  216. } else if(!caseSensitve && !wholeWorlds ){
  217. if(lineUpper.Contains(expresion.ToUpper()) )
  218. result.Add(indx,line);
  219. } else if(!caseSensitve && wholeWorlds){
  220. if(lineUpper.Split(separators).Contains(expresion.ToUpper()))
  221. result.Add(indx,line);
  222. } else if(caseSensitve && wholeWorlds){
  223. if(line.Split(separators).Contains(expresion))
  224. result.Add(indx,line);
  225. }*/
  226. //line.Contains("string", StringComparison.CurrentCultureIgnoreCase);
  227. indx++;
  228. } while (reader.Peek() != -1);
  229. reader.Close();
  230. if (isChanged)
  231. try {
  232. StreamWriter writer = new StreamWriter(filePath);
  233. writer.Write(sb.ToString());
  234. writer.Close();
  235. } catch (Exception ex) {
  236. Tool.Logger.Error(ex.Message);
  237. }
  238. return result;
  239. }
  240. public static bool IsWordSeparator(char ch)
  241. {
  242. return !Char.IsLetterOrDigit(ch) && ch != '_';
  243. }
  244. public static bool ContainsPath(string baseDirectoryPath, string secondPath)
  245. {
  246. // Remove trailing '.'
  247. baseDirectoryPath = TrimTrailingDotCharacter(baseDirectoryPath);
  248. // Remove trailing directory separators.
  249. baseDirectoryPath = TrimTrailingDirectorySeparator(baseDirectoryPath);
  250. secondPath = TrimTrailingDirectorySeparator(secondPath);
  251. // Remove ".\" occurrences.
  252. secondPath = secondPath.Replace(String.Concat(".", separators [0]), String.Empty);
  253. secondPath = secondPath.Replace(String.Concat(".", separators [1]), String.Empty);
  254. string[] bPath = baseDirectoryPath.Split(separators);
  255. string[] aPath = secondPath.Split(separators);
  256. int indx = 0;
  257. for (; indx < Math.Min(bPath.Length, aPath.Length); ++indx)
  258. if (String.Compare(bPath [indx], aPath [indx], true) != 0)//if(!bPath[indx].Equals(aPath[indx]))
  259. break;
  260. if (indx == bPath.Length)
  261. return true;
  262. return false;
  263. }
  264. public static void GetAllFiles(ref List<string> filesList,string path)
  265. {
  266. if (!Directory.Exists(path))
  267. return;
  268. DirectoryInfo di = new DirectoryInfo(path);
  269. foreach (DirectoryInfo d in di.GetDirectories()) {
  270. int indx = -1;
  271. indx = MainClass.Settings.IgnoresFolders.FindIndex(x => x.Folder == d.Name && x.IsForIde);
  272. if (indx < 0)
  273. GetAllFiles(ref filesList, d.FullName);
  274. }
  275. foreach (FileInfo f in di.GetFiles()){
  276. int indx = -1;
  277. indx = MainClass.Settings.IgnoresFiles.FindIndex(x => x.Folder == f.Name && x.IsForIde);
  278. if(indx >-1)continue;
  279. filesList.Add(f.FullName);
  280. }
  281. }
  282. public static string DeleteItem(string fileName, bool isDir)
  283. {
  284. if (isDir) {
  285. if (!System.IO.Directory.Exists(fileName))
  286. return "";
  287. try {
  288. List<string> listFile = new List<string>();
  289. GetAllFiles(ref listFile, fileName);
  290. System.IO.Directory.Delete(fileName, true);
  291. foreach (string file in listFile)
  292. MainClass.MainWindow.EditorNotebook.ClosePage(file, true);
  293. } catch (Exception ex){
  294. return ex.Message;
  295. }
  296. } else {
  297. if (!System.IO.File.Exists(fileName))
  298. return "";
  299. try {
  300. System.IO.File.Delete(fileName);
  301. MainClass.MainWindow.EditorNotebook.ClosePage(fileName, true);
  302. } catch (Exception ex) {
  303. return ex.Message;
  304. }
  305. }
  306. return "";
  307. }
  308. public static string RenameItem(string fileName, bool isDir, string newName,out string newPath)
  309. {
  310. newPath = "";
  311. if (isDir) {
  312. if (!System.IO.Directory.Exists(fileName)){
  313. return "";
  314. }
  315. string path = System.IO.Path.GetDirectoryName(fileName);
  316. newPath = System.IO.Path.Combine(path, newName);
  317. if (System.IO.Directory.Exists(newPath)){
  318. return "";
  319. }
  320. try {
  321. List<string> listFile = new List<string>();
  322. FileUtility.GetAllFiles(ref listFile, fileName);
  323. foreach (string file in listFile)
  324. MainClass.MainWindow.EditorNotebook.ClosePage(file, true);
  325. System.IO.Directory.Move(fileName, newPath);
  326. } catch(Exception ex) {
  327. return ex.Message;
  328. }
  329. } else {// Rename File
  330. if (!System.IO.File.Exists(fileName)){
  331. return "";
  332. }
  333. string path = System.IO.Path.GetDirectoryName(fileName);
  334. string extension = System.IO.Path.GetExtension(fileName);
  335. string newExt = System.IO.Path.GetExtension(newName);
  336. if (string.IsNullOrEmpty(newExt))
  337. newName = newName + extension;
  338. newPath = System.IO.Path.Combine(path, newName);
  339. if (System.IO.Directory.Exists(newPath)){
  340. return "";
  341. }
  342. try {
  343. System.IO.File.Move(fileName, newPath);
  344. MainClass.MainWindow.EditorNotebook.RenameFile(fileName, newPath);
  345. } catch (Exception ex){
  346. return ex.Message;
  347. }
  348. }
  349. return "";
  350. }
  351. public static void CreateDirectory(string newFile)
  352. {
  353. string fileName = System.IO.Path.GetFileName(newFile);
  354. string dir = System.IO.Path.GetDirectoryName (newFile);
  355. if (System.IO.Directory.Exists(newFile))
  356. newFile = System.IO.Path.Combine(dir, fileName+"_1");
  357. Directory.CreateDirectory(newFile);
  358. }
  359. public static void CreateFile(string newFile, string content)
  360. {
  361. string dir = System.IO.Path.GetDirectoryName(newFile);
  362. string nameExtens = System.IO.Path.GetExtension(newFile);
  363. string nameClear = System.IO.Path.GetFileNameWithoutExtension(newFile);
  364. if (System.IO.File.Exists(newFile))
  365. newFile = System.IO.Path.Combine(dir, nameClear+"_1"+nameExtens);
  366. string ext = System.IO.Path.GetExtension(newFile);
  367. if (ext == ".db"){
  368. using (FileStream fs = System.IO.File.Create(newFile))
  369. fs.Close();
  370. SqlLiteDal sqlld = new SqlLiteDal(newFile);
  371. //Console.WriteLine(content);
  372. sqlld.RunSqlScalar(content);
  373. } else {
  374. using (StreamWriter file = new StreamWriter(newFile)) {
  375. file.Write(content);
  376. file.Close();
  377. file.Dispose();
  378. }
  379. }
  380. }
  381. #region private
  382. private static bool IsWholeWordAt(string text, int offset, int length)
  383. {
  384. return (offset <= 0 || IsWordSeparator(text [offset - 1])) &&
  385. (offset + length >= text.Length || IsWordSeparator(text [offset + length]));
  386. }
  387. private static void Replace(ref string text, int offset, int length, string replacement)
  388. {
  389. text = text.Remove(offset, length);
  390. text = text.Insert(offset, replacement);
  391. /*if (document != null) {
  392. Gtk.Application.Invoke (delegate {
  393. document.Editor.Replace (offset, length, replacement);
  394. });
  395. return;
  396. }*/
  397. }
  398. #endregion
  399. }
  400. }