How to display C# source code from external file?

2019-05-06 05:19发布

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?

3条回答
Rolldiameter
2楼-- · 2019-05-06 05:24

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.

查看更多
再贱就再见
3楼-- · 2019-05-06 05:36

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

alt text

查看更多
劳资没心,怎么记你
4楼-- · 2019-05-06 05:37

Another take on syntax highlighting.

查看更多
登录 后发表回答