Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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