Skip to content

Instantly share code, notes, and snippets.

@RickStrahl
Last active October 11, 2021 02:15
Show Gist options
  • Save RickStrahl/38b2072c210c402e1ed919692ad1f56c to your computer and use it in GitHub Desktop.
Save RickStrahl/38b2072c210c402e1ed919692ad1f56c to your computer and use it in GitHub Desktop.
Demonstrates different ways to launch VS Code from C# code on Windows
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