Last active
October 11, 2021 02:15
-
-
Save RickStrahl/38b2072c210c402e1ed919692ad1f56c to your computer and use it in GitHub Desktop.
Demonstrates different ways to launch VS Code from C# code on Windows
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
string file = @"C:\temp\test.md"; | |
OpenFileInTextEditorRegistry(file); | |
//OpenEditorWithShellExecute(file); | |
//OpenWithProcessStartFailed(file); | |
} | |
public static void OpenFileInTextEditorRegistry(string filename) | |
{ | |
string executable = "notepad.exe"; | |
var keyValue = Registry.ClassesRoot.OpenSubKey(@"Applications\Code.exe\shell\open\command")?.GetValue(null) as string; | |
if (keyValue != null && keyValue.Contains("code.exe",StringComparison.InvariantCultureIgnoreCase)) | |
{ | |
executable = StringUtils.ExtractString(keyValue,@"""",@""""); | |
} | |
var pi = new ProcessStartInfo | |
{ | |
UseShellExecute = true, | |
FileName = executable, | |
Arguments = filename, | |
}; | |
var res = Process.Start(pi); | |
} | |
public static void OpenEditorWithShellExecute(string filename) | |
{ | |
var pi = new ProcessStartInfo | |
{ | |
UseShellExecute = true, | |
FileName = "code", // "invalid_codePath" - should start Notepad | |
Arguments = filename, | |
WindowStyle = ProcessWindowStyle.Hidden | |
}; | |
try | |
{ | |
var res = Process.Start(pi); | |
} | |
catch(Exception ex) | |
{ | |
pi.WindowStyle = ProcessWindowStyle.Normal; | |
pi.FileName = "notepad.exe"; | |
var res = Process.Start(pi); | |
} | |
} | |
public static void OpenWithProcessStartFailed(string filename) | |
{ | |
var pi = new ProcessStartInfo | |
{ | |
FileName = "code", | |
Arguments = filename, | |
}; | |
var res = Process.Start(pi); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment