Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to launch a process which will open a text file in any editor and automatically move cursor to a certain line number?

Tags:

c#

From c#, I want to launch a process which will open a text file in any editor and automatically move cursor to a certain line number.

I can open a file using

Process.Start(@"c:\myfile.txt");

but I don't know how to move cursor at specific location in that file.


Answer with source code:

yes, I used notepad++

private void openLog() {
            try {
                // see if notepad++ is installed on user's machine
                var nppDir = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Notepad++", null, null);
                if (nppDir != null) {
                    var nppExePath = Path.Combine(nppDir, "Notepad++.exe");
                    var nppReadmePath = Path.Combine(yourDirectory,fileName );
                    var line = 20;
                    var sb = new StringBuilder();
                    sb.AppendFormat("\"{0}\" -n{1}", nppReadmePath, lineNo);
                    Process.Start(nppExePath, sb.ToString());
                } else {
                    string newPath = @"\\mySharedDrive\notpad++\bin\notepad++.exe";
                    Process.Start(newPath, @"\\" + filePath + " -n" + lineNo); // take exe from my shared drive
                }
            } catch (Exception e) {
                Process.Start(@"\\" + FilePath); // open using notepad
            }
        }
like image 411
Andan Desai Avatar asked Dec 07 '12 00:12

Andan Desai


1 Answers

Get Notepad++, then you can do this:

    var nppDir = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Notepad++", null, null);
    var nppExePath = Path.Combine(nppDir, "Notepad++.exe");
    var nppReadmePath = Path.Combine(nppDir, "readme.txt");
    var line = 20;
    var sb = new StringBuilder();
    sb.AppendFormat("\"{0}\" -n{1}", nppReadmePath, line);
    Process.Start(nppExePath, sb.ToString());

In this example we get install path of n++ from the registry, build path to exe and readme.txt file, opens its own readme.txt file with cursor on line 20. Using StringBuilder is more efficient than using multiple appends (explanation somewhere on SO).

like image 179
Mike Trusov Avatar answered Oct 20 '22 01:10

Mike Trusov