|
| 1 | +using System.IO; |
| 2 | + |
| 3 | +namespace CSharpScriptOperations; |
| 4 | + |
| 5 | +public static partial class OperationUtils |
| 6 | +{ |
| 7 | + public static class IO |
| 8 | + { |
| 9 | + static string _workingDirBase = AppDomain.CurrentDomain.BaseDirectory; |
| 10 | + |
| 11 | + /// <summary> |
| 12 | + /// Change the working directory base throughout the application. |
| 13 | + /// Be default, this is the directory of the executable. |
| 14 | + /// </summary> |
| 15 | + /// <param name="path">Absolute path</param> |
| 16 | + public static void SetWorkingDirBase(params string[] path) |
| 17 | + { |
| 18 | + _workingDirBase = Path.Combine(path); |
| 19 | + } |
| 20 | + |
| 21 | + /// <summary> |
| 22 | + /// Prepare the directory tree for a path and return whether the file or directory exists. |
| 23 | + /// </summary> |
| 24 | + /// <param name="pathIsDir"></param> |
| 25 | + /// <param name="makeMissingDir"></param> |
| 26 | + /// <returns>True when the path exists as a file or directory based on pathIsDir</returns> |
| 27 | + public static bool EnsureValidPath(string path, bool pathIsDir, bool makeMissingDir = true) |
| 28 | + { |
| 29 | + string dir = pathIsDir ? path : Path.GetDirectoryName(path); |
| 30 | + if (makeMissingDir && !Directory.Exists(dir)) |
| 31 | + Directory.CreateDirectory(dir); |
| 32 | + |
| 33 | + // Check if the file already exists |
| 34 | + return pathIsDir ? Directory.Exists(path) : File.Exists(path); |
| 35 | + } |
| 36 | + |
| 37 | + /// <summary> |
| 38 | + /// Returns a path relative to the working directory. |
| 39 | + /// Working directory can be changed with SetWorkingDirBase() on startup. |
| 40 | + /// </summary> |
| 41 | + /// <param name="parts"></param> |
| 42 | + /// <returns></returns> |
| 43 | + public static string GetWorkingPath(params string[] parts) |
| 44 | + { |
| 45 | + string[] finalParts = new string[parts.Length + 1]; |
| 46 | + finalParts[0] = _workingDirBase; |
| 47 | + for (int i = 0; i < parts.Length; i++) |
| 48 | + finalParts[i + 1] = parts[i]; |
| 49 | + return Path.Combine(finalParts); |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | +} |
0 commit comments