简体   繁体   中英

How to display C# source code from external file?

For my project I'd like to display C# source code that I get from an external file. All I want to do is to parse that file and if possible display the code with syntax highlighting.

If also possible I'd like to divide the code I read into the various methods.

Where should I start?

I'd recommend AvalonEdit . It's easy to setup and use. Example

xmlns:avalonEdit="http://icsharpcode.net/sharpdevelop/avalonedit"

<avalonEdit:TextEditor Name="textEditor"
                       Loaded="textEditor_Loaded"
                       FontFamily="Consolas"
                       FontSize="10pt"/>

private void textEditor_Loaded(object sender, RoutedEventArgs e)
{
    textEditor.Load(@"C:\MainWindow.xaml.cs");
    textEditor.SyntaxHighlighting =
        HighlightingManager.Instance.GetDefinition("C#");
}

Example Output

替代文字

An alternative way is to launch an external tool or app like viewer. For example, in Windows you can use VIM app to open a cs file in read-only and no modification mode:

"C:\Program Files\Vim\vim72\gvim.exe" -R -M C:\test\MyClass.cs

Here are some codes to launch the tool:

public static int StartViewer(string file)
    {
        string parameters = string.Format("-R -M {0}", file);
        ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo();
        psi.FileName = "C:\Program Files\Vim\vim72\gvim.exe";
        psi.Arguments = parameters;

        Process p = Process.Start(psi);
        p.WaitForExit();

        return p.ExitCode;
    }

I think VIM has CS syntax colorizer, or you can find some better one. It is free and has great search feature. However, VIM may not be good for none-VIM users. This is just an example. You can use other tools if you like to leverage other app strength.

另一种语法突出显示

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM