简体   繁体   中英

Replace statement using roslyn

I am trying to update a statment in my file. my requirement is to update

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

to

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

I am using following code:

 // 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());
            }

but the result of the above is:

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

the statement starts from the left and even "}" bracket comes on the same line. Any suggestions?

You will need to copy the SyntaxTrivia from the old statement to the new one.

BTW: It would probably be better to do a weaker check for the node you want to replace, and to replace only the LiteralExpressionSyntax for "Hub". Otherwise any white space in the original will mess you up, and you will remove any other formatting/comments/etc in the statement you are replacing.

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