Skip to content

Instantly share code, notes, and snippets.

@derekantrican
Last active May 13, 2022 22:57
Show Gist options
  • Save derekantrican/8f348d1ff572a9e622e9141c863cdadf to your computer and use it in GitHub Desktop.
Save derekantrican/8f348d1ff572a9e622e9141c863cdadf to your computer and use it in GitHub Desktop.
Code to open Visual Studio to a specific line in a file
using System;
using System.Runtime.InteropServices;
//Usage: VSToLine.exe [full path to file] [line number] (eg VSToLine.exe fullPathToFile.cs 10)
//Original source: https://newbedev.com/open-a-file-in-visual-studio-at-a-specific-line-number
//Needed references:
// https://www.nuget.org/packages/envdte/17.2.32505.113
// https://www.nuget.org/packages/envdte80/17.2.32505.113
// https://www.nuget.org/packages/stdole/17.2.32505.113
namespace VSToLine
{
class Program
{
static void Main(string[] args)
{
try
{
string filename = args[0];
int fileline = 0;
if (args.Length > 1)
int.TryParse(args[1], out fileline);
//You can also just use 'VSToLine.exe fullPathToFile.cs:line 10' as sometimes that
//is the format given when I was working on this in the past
int iPos = filename.IndexOf(":line ");
if (iPos > 0)
{
string sLineNumber = filename.Substring(iPos + 6);
int.TryParse(sLineNumber, out fileline);
filename = filename.Remove(iPos);
}
string progID = "VisualStudio.DTE.16.0";
//Note that you may need to change this string depending on the VS version.
//I found that having VS open and running https://stackoverflow.com/a/7738455/2246411
//helped me find which id I should be using (but there may be a simpler example out there)
EnvDTE80.DTE2 dte2 = (EnvDTE80.DTE2)Marshal.GetActiveObject(progID);
dte2.MainWindow.Activate();
EnvDTE.Window w = dte2.ItemOperations.OpenFile(filename, EnvDTE.Constants.vsViewKindTextView);
if (fileline > 0)
((EnvDTE.TextSelection)dte2.ActiveDocument.Selection).GotoLine(fileline, true);
}
catch (Exception e)
{
Console.WriteLine(e.Message);
Console.WriteLine(e.StackTrace);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment