2

我正在尝试更新文件中的语句。我的要求是更新

protected override void OnLaunchApplication(LaunchActivatedEventArgs args)
    {
        NavigationService.Navigate("Hub", null);
    }

protected override void OnLaunchApplication(LaunchActivatedEventArgs args)
    {
        NavigationService.Navigate("Main", null);
    }

我正在使用以下代码:

 // read file contents
            string fileContent = File.ReadAllText(targetFile);

            // create syntax tree
            SyntaxTree tree = SyntaxTree.ParseText(fileContent);

            // locate OnLaunchApplication event
            var targetMethod =
                tree.GetRoot()
                    .DescendantNodes()
                    .OfType<MethodDeclarationSyntax>()
                    .FirstOrDefault(x => (string)x.Identifier.Value == "OnLaunchApplication");

            if (targetMethod != null)
            {
                StatementSyntax oldSyntax = targetMethod.DescendantNodes()
                    .OfType<StatementSyntax>()
                    .FirstOrDefault(x => x.ToString() == @"NavigationService.Navigate(""Hub"", null);");

                StatementSyntax newHubSyntax = Syntax.ParseStatement(@"NavigationService.Navigate(""Main"", null);");

                CompilationUnitSyntax newRoot = tree.GetRoot().ReplaceNode(oldSyntax, newHubSyntax);

                File.WriteAllText(targetFile, newRoot.ToFullString());
            }

但上面的结果是:

 protected override void OnLaunchApplication(LaunchActivatedEventArgs args)
    {
NavigationService.Navigate("Main", null);        }

语句从左边开始,甚至“}”括号也出现在同一行。有什么建议么?

4

1 回答 1

3

您需要将SyntaxTrivia旧语句中的语句复制到新语句中。

顺便说一句:最好对要替换的节点进行较弱的检查,并仅替换LiteralExpressionSyntax“集线器”。否则,原件中的任何空白都会让您感到困惑,并且您将删除要替换的语句中的任何其他格式/注释/等。

于 2013-09-30T14:27:23.270 回答