EasySign BETA
Digital Signing Tool
Loading...
Searching...
No Matches
Utilities.cs
Go to the documentation of this file.
1using System.Collections.Concurrent;
2using System.Security.Cryptography.X509Certificates;
3
4using Spectre.Console;
5
7{
11 internal static class Utilities
12 {
18 public static void RunInStatusContext(string initialStatus, Action<StatusContext> action)
19 {
20 AnsiConsole.Status()
21 .AutoRefresh(true)
22 .Spinner(Spinner.Known.Default)
23 .Start(initialStatus, action);
24 }
25
38 public static bool IsFileWithinRoot(string filePath, string rootPath)
39 {
40 // Get the full absolute paths
41 string absoluteFilePath = Path.GetFullPath(filePath);
42 string absoluteRootPath = Path.GetFullPath(rootPath);
43
44 // Ensure the root path ends with a directory separator
45 if (!absoluteRootPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
46 {
47 absoluteRootPath += Path.DirectorySeparatorChar;
48 }
49
50 // Check if the file path starts with the root path (using OrdinalIgnoreCase for case-insensitive comparison on Windows)
51 return absoluteFilePath.StartsWith(absoluteRootPath, StringComparison.OrdinalIgnoreCase);
52 }
53
61 public static IEnumerable<string> SafeEnumerateFiles(string path, string searchPattern, bool recursive = true)
62 {
63 ConcurrentQueue<string> folders = new();
64 folders.Enqueue(path);
65
66 while (!folders.IsEmpty)
67 {
68 if (!folders.TryDequeue(out string? currentDir)) continue;
69
70 string[] subDirs = Array.Empty<string>();
71 string[] files = Array.Empty<string>();
72
73 try
74 {
75 files = Directory.GetFiles(currentDir, searchPattern);
76 }
77 catch (UnauthorizedAccessException) { }
78 catch (DirectoryNotFoundException) { }
79
80 foreach (string file in files)
81 {
82 yield return file;
83 }
84
85 try
86 {
87 if (recursive)
88 {
89 subDirs = Directory.GetDirectories(currentDir);
90 }
91 }
92 catch (UnauthorizedAccessException) { continue; }
93 catch (DirectoryNotFoundException) { continue; }
94
95 foreach (string dir in subDirs)
96 {
97 folders.Enqueue(dir);
98 }
99 }
100 }
101
107 public static string SecurePrompt(string prompt)
108 {
109 return AnsiConsole.Prompt(
110 new TextPrompt<string>(prompt)
111 .PromptStyle("red")
112 .AllowEmpty()
113 .Secret(null));
114 }
115
120 public static void EnumerateStatuses(X509ChainStatus[] statuses)
121 {
122 foreach (X509ChainStatus status in statuses)
123 {
124 AnsiConsole.MarkupLine($"[{Color.IndianRed}] {status.StatusInformation}[/]");
125 }
126 }
127
138 public static bool ParseToBool(string input)
139 {
140 if (int.TryParse(input, out int number))
141 {
142 return number == 1;
143 }
144 if (bool.TryParse(input, out bool boolean))
145 {
146 return boolean;
147 }
148
149 throw new FormatException($"Cannot convert '{input}' to a boolean.");
150 }
151 }
152}