-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ShellUtils.cs
638 lines (565 loc) · 22.9 KB
/
ShellUtils.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
#region
/*
**************************************************************
* Author: Rick Strahl
* © West Wind Technologies, 2011-2023
* http://www.west-wind.com/
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
**************************************************************
*/
#endregion
using System;
using System.Text;
using System.IO;
using System.Net;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace Westwind.Utilities
{
/// <summary>
/// Windows specific shell utility functions
/// </summary>
public static class ShellUtils
{
#region Open in or Start Process
/// <summary>
/// Opens a File or Folder in Explorer. If the path is a file
/// Explorer is opened in the parent folder with the file selected
/// </summary>
/// <param name="filename"></param>
public static bool OpenFileInExplorer(string filename)
{
if (string.IsNullOrEmpty(filename))
return false;
if (Directory.Exists(filename))
ShellUtils.GoUrl(filename);
else
{
// required as command Explorer command line doesn't allow mixed slashes
filename = Path.GetFullPath(filename);
if (!File.Exists(filename))
filename = Path.GetDirectoryName(filename);
try
{
Process.Start("explorer.exe", $"/select,\"{filename}\"");
}
catch
{
return false;
}
}
return true;
}
/// <summary>
/// Executes a Windows process with given command line parameters
/// </summary>
/// <param name="executable">Executable to run</param>
/// <param name="arguments">Command Line Parameters passed to executable</param>
/// <param name="timeoutMs">Timeout of the process in milliseconds. Pass -1 to wait forever. Pass 0 to not wait.</param>
/// <param name="windowStyle">Hidden, Normal etc.</param>
/// <returns>process exit code or 0 if run and forget. 1460 for time out. -1 on error</returns>
public static int ExecuteProcess(string executable,
string arguments = null,
int timeoutMs = 0,
ProcessWindowStyle windowStyle = ProcessWindowStyle.Hidden)
{
Process process;
try
{
using (process = new Process())
{
process.StartInfo.FileName = executable;
process.StartInfo.Arguments = arguments;
process.StartInfo.WindowStyle = windowStyle;
if (windowStyle == ProcessWindowStyle.Hidden)
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.Start();
if (timeoutMs < 0)
timeoutMs = 99999999; // indefinitely
if (timeoutMs > 0)
{
if (!process.WaitForExit(timeoutMs))
{
Console.WriteLine("Process timed out.");
return 1460;
}
}
else // run and don't wait - no exit code
return 0;
return process.ExitCode;
}
}
catch (Exception ex)
{
Console.WriteLine("Error executing process: " + ex.Message);
return -1; // unhandled error
}
}
/// <summary>
/// Executes a Windows process with given command line parameters
/// and captures console output into a string.
///
/// Writes command output to the output StringBuilder
/// from StdOut and StdError.
/// </summary>
/// <param name="executable">Executable to run</param>
/// <param name="arguments">Command Line Parameters passed to executable</param>
/// <param name="timeoutMs">Timeout of the process in milliseconds. Pass -1 to wait forever. Pass 0 to not wait.</param>
/// <param name="output">Pass in a string reference that will receive StdOut and StdError output</param>
/// <param name="windowStyle">Hidden, Normal, etc.</param>
/// <returns>process exit code or 0 if run and forget. 1460 for time out. -1 on error</returns>
public static int ExecuteProcess(string executable,
string arguments,
int timeoutMs,
out StringBuilder output,
ProcessWindowStyle windowStyle = ProcessWindowStyle.Hidden)
{
return ExecuteProcess(executable, arguments, timeoutMs, out output, null, windowStyle);
}
/// <summary>
/// Executes a Windows process with given command line parameters
/// and captures console output into a string.
///
/// Pass in a String Action that receives output from
/// StdOut and StdError as it is written (one line at a time).
/// </summary>
/// <param name="executable">Executable to run</param>
/// <param name="arguments">Command Line Parameters passed to executable</param>
/// <param name="timeoutMs">Timeout of the process in milliseconds. Pass -1 to wait forever. Pass 0 to not wait.</param>
/// <param name="writeDelegate">Delegate to let you capture streaming output of the executable to stdout and stderror.</param>
/// <param name="windowStyle">Hidden, Normal etc.</param>
/// <returns>process exit code or 0 if run and forget. 1460 for time out. -1 on error</returns>
public static int ExecuteProcess(string executable,
string arguments,
int timeoutMs,
Action<string> writeDelegate,
ProcessWindowStyle windowStyle = ProcessWindowStyle.Hidden)
{
return ExecuteProcess(executable, arguments, timeoutMs, out StringBuilder output, writeDelegate, windowStyle);
}
/// <summary>
/// Executes a Windows process with given command line parameters
/// and captures console output into a string.
///
/// Writes original output into the application Console which you can
/// optionally redirect to capture output from the command line
/// operation using `Console.SetOut` or `Console.SetError`.
/// </summary>
/// <param name="executable">Executable to run</param>
/// <param name="arguments"></param>
/// <param name="timeoutMs">Timeout of the process in milliseconds. Pass -1 to wait forever. Pass 0 to not wait.</param>
/// <param name="output">StringBuilder that will receive StdOut and StdError output</param>
/// <param name="writeDelegate">Action to capture stdout and stderror output for you to handle</param>
/// <param name="windowStyle"></param>
/// <returns>process exit code or 0 if run and forget. 1460 for time out. -1 on error</returns>
private static int ExecuteProcess(string executable,
string arguments,
int timeoutMs,
out StringBuilder output,
Action<string> writeDelegate = null,
ProcessWindowStyle windowStyle = ProcessWindowStyle.Hidden)
{
Process process;
try
{
using (process = new Process())
{
process.StartInfo.FileName = executable;
process.StartInfo.Arguments = arguments;
process.StartInfo.WindowStyle = windowStyle;
if (windowStyle == ProcessWindowStyle.Hidden)
process.StartInfo.CreateNoWindow = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
var sb = new StringBuilder();
process.OutputDataReceived += (sender, args) =>
{
if (writeDelegate != null)
writeDelegate.Invoke(args.Data);
else
sb.AppendLine(args.Data);
};
process.ErrorDataReceived += (sender, args) =>
{
if (writeDelegate != null)
writeDelegate.Invoke(args.Data);
else
sb.AppendLine(args.Data);
};
process.Start();
process.BeginErrorReadLine();
process.BeginOutputReadLine();
if (timeoutMs < 0)
timeoutMs = 99999999; // indefinitely
if (timeoutMs > 0)
{
if (!process.WaitForExit(timeoutMs))
{
Console.WriteLine("Process timed out.");
output = null;
return 1460;
}
}
else
{
// no exit code
output = sb;
return 0;
}
output = sb;
return process.ExitCode;
}
}
catch (Exception ex)
{
Console.WriteLine($"Error executing process: {ex.Message}");
output = null;
return -1; // unhandled error
}
}
/// <summary>
/// Opens a Terminal window in the specified folder
/// </summary>
/// <param name="folder"></param>
/// <param name="mode">Powershell, Command or Bash</param>
/// <returns>false if process couldn't be started - most likely invalid link</returns>
public static bool OpenTerminal(string folder, TerminalModes mode = TerminalModes.Powershell)
{
try
{
string cmd = null, args = null;
if (mode == TerminalModes.Powershell)
{
cmd = "powershell.exe";
args = "-noexit -command \"cd '{0}'\"";
}
else if (mode == TerminalModes.Command)
{
cmd = "cmd.exe";
args = "/k \"cd {0}\"";
}
Process.Start(cmd, string.Format(args, folder));
}
catch
{
return false;
}
return true;
}
#endregion
#region Shell Execute Apis, URL Openening
/// <summary>
/// Uses the Shell Extensions to launch a program based on URL moniker or file name
/// Basically a wrapper around ShellExecute
/// </summary>
/// <param name="url">Any URL Moniker that the Windows Shell understands (URL, Word Docs, PDF, Email links etc.)</param>
/// <returns></returns>
public static bool GoUrl(string url, string workingFolder = null)
{
if (string.IsNullOrEmpty(workingFolder))
return OpenUrl(url);
string TPath = Path.GetTempPath();
ProcessStartInfo info = new ProcessStartInfo();
info.UseShellExecute = true;
info.Verb = "Open";
info.WorkingDirectory = TPath;
info.FileName = url;
bool result;
using (Process process = new Process())
{
process.StartInfo = info;
try
{
result = process.Start();
}
catch
{
return false;
}
}
return result;
}
/// <summary>
/// Opens a URL in the browser. This version is specific to opening
/// a URL in a browser and it's cross platform enabled.
/// </summary>
/// <param name="url"></param>
public static bool OpenUrl(string url)
{
bool success = true;
#if NETCORE
bool isWindows = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) || RuntimeInformation.OSDescription.Contains("microsoft-standard");
#else
bool isWindows = true;
#endif
Process p = null;
try
{
var psi = new ProcessStartInfo(url);
psi.UseShellExecute = isWindows; // must be explicit -defaults changed in NETFX & NETCORE
p = Process.Start(psi);
}
catch
{
#if NETCORE
// hack because of this: https://github.com/dotnet/corefx/issues/10361
if (isWindows)
{
url = url.Replace("&", "^&");
try
{
Process.Start(new ProcessStartInfo("cmd.exe", $"/c start {url}") {CreateNoWindow = true});
}
catch
{
success = false;
}
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
{
p = Process.Start("xdg-open", url);
}
else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
p = Process.Start("open", url);
}
else
{
success = false;
}
#else
success = false;
#endif
}
p?.Dispose();
return success;
}
/// <summary>
/// Wrapper around the Shell Execute API. Windows specific.
/// </summary>
/// <param name="url"></param>
/// <param name="arguments"></param>
/// <param name="workingFolder"></param>
/// <param name="verb"></param>
/// <returns></returns>
public static int ShellExecute(string url, string arguments = null,
string workingFolder = null, string verb = "Open")
{
ProcessStartInfo info = new ProcessStartInfo();
info.UseShellExecute = true;
info.Verb = "Open";
info.FileName = url;
info.Arguments = arguments;
info.WorkingDirectory = workingFolder;
using (Process process = new Process())
{
process.StartInfo = info;
process.Start();
}
return 0;
}
/// <summary>
/// Executes a Windows Command Line using Shell Execute as a
/// single command line with parameters. This method handles
/// parsing out the executable from the parameters.
/// </summary>
/// <param name="fullCommandLine">Full command line - Executable plus arguments.
/// If the executable contains paths with spaces **make sure to add quotes around the executable** otherwise the executable may not be found.
/// </param>
/// <param name="workingFolder">Optional - the folder the executable runs in. If not specified uses current folder.</param>
/// <param name="waitForExitMs">Optional - Number of milliseconds to wait for completion. 0 don't wait.</param>
/// <param name="verb">Optional - Shell verb to apply. Defaults to "Open"</param>
/// <param name="windowStyle">Optional - Windows style for the launched application. Default style is normal</param>
/// <remarks>
/// If the executable or parameters contain or **may contain spaces** make sure you use quotes (") or (') around the exec or parameters.
/// </remarks>
public static void ExecuteCommandLine(string fullCommandLine,
string workingFolder = null,
int waitForExitMs = 0,
string verb = "OPEN",
ProcessWindowStyle windowStyle = ProcessWindowStyle.Normal,
bool useShellExecute = true)
{
string executable = fullCommandLine;
string args = null;
if (executable.StartsWith("\""))
{
int at = executable.IndexOf("\" ");
if (at > 0)
{
args = executable.Substring(at + 1).Trim();
executable = executable.Substring(0, at);
}
}
else
{
int at = executable.IndexOf(" ");
if (at > 0)
{
if (executable.Length > at + 1)
args = executable.Substring(at + 1).Trim();
executable = executable.Substring(0, at);
}
}
var pi = new ProcessStartInfo
{
Verb = verb,
WindowStyle = windowStyle,
FileName = executable,
WorkingDirectory = workingFolder,
Arguments = args,
UseShellExecute = true
};
using (var p = Process.Start(pi))
{
if (waitForExitMs > 0)
{
if (!p.WaitForExit(waitForExitMs))
throw new TimeoutException("Process failed to complete in time.");
}
}
}
/// <summary>
/// Displays a string in in a browser as HTML. Optionally
/// provide an alternate extension to display in the appropriate
/// text viewer (ie. "txt" likely shows in NotePad)
/// </summary>
/// <param name="text"></param>
/// <param name="extension"></param>
/// <returns></returns>
public static bool ShowString(string text, string extension = null)
{
if (extension == null)
extension = "htm";
string File = Path.GetTempPath() + "\\__preview." + extension;
StreamWriter sw = new StreamWriter(File, false, Encoding.Default);
sw.Write(text);
sw.Close();
return GoUrl(File);
}
/// <summary>
/// Shows a string as HTML
/// </summary>
/// <param name="htmlString"></param>
/// <returns></returns>
public static bool ShowHtml(string htmlString)
{
return ShowString(htmlString, null);
}
/// <summary>
/// Displays a large Text string as a text file in the
/// systems' default text viewer (ie. NotePad)
/// </summary>
/// <param name="TextString"></param>
/// <returns></returns>
public static bool ShowText(string TextString)
{
string File = Path.GetTempPath() + "\\__preview.txt";
StreamWriter sw = new StreamWriter(File, false);
sw.Write(TextString);
sw.Close();
return GoUrl(File);
}
#endregion
#region Simple HTTP Helpers
/// <summary>
/// Simple method to retrieve HTTP content from the Web quickly
/// </summary>
/// <param name="url">Url to access</param>
/// <returns>Http response text or null</returns>
public static string HttpGet(string url)
{
string errorMessage;
return HttpGet(url, out errorMessage);
}
/// <summary>
/// Simple method to retrieve HTTP content from the Web quickly
/// </summary>
/// <param name="url">Url to access</param>
/// <param name="errorMessage"></param>
/// <returns></returns>
public static string HttpGet(string url, out string errorMessage)
{
string responseText = string.Empty;
errorMessage = null;
using (WebClient Http = new WebClient())
{
try
{
responseText = Http.DownloadString(url);
}
catch (Exception ex)
{
errorMessage = ex.Message;
return null;
}
}
return responseText;
}
/// <summary>
/// Retrieves a buffer of binary data from a URL using
/// a plain HTTP Get.
/// </summary>
/// <param name="url">Url to access</param>
/// <returns>Response bytes or null on error</returns>
public static byte[] HttpGetBytes(string url)
{
string errorMessage;
return HttpGetBytes(url, out errorMessage);
}
/// <summary>
/// Retrieves a buffer of binary data from a URL using
/// a plain HTTP Get.
/// </summary>
/// <param name="url">Url to access</param>
/// <param name="errorMessage">ref parm to receive an error message</param>
/// <returns>response bytes or null on error</returns>
public static byte[] HttpGetBytes(string url, out string errorMessage)
{
byte[] result = null;
errorMessage = null;
using (var http = new WebClient())
{
try
{
result = http.DownloadData(url);
}
catch (Exception ex)
{
errorMessage = ex.Message;
return null;
}
}
return result;
}
#endregion
}
public enum TerminalModes
{
Powershell,
Command,
Bash
}
}