我正在尝试更新文件中的语句。我的要求是更新
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); }
语句从左边开始,甚至“}”括号也出现在同一行。有什么建议么?