我正在尝试更新文件中的状态。我的要求是更新
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); }
语句从左边开始,偶数“}”括号出现在同一行。 有什么建议吗?
答案 0 :(得分:3)
您需要将旧语句中的SyntaxTrivia
复制到新语句中。
顺便说一句:对要替换的节点进行较弱的检查可能会更好,并且只替换{Hub}的LiteralExpressionSyntax
。否则原件中的任何空白区域都会弄乱您,并且您将删除要替换的语句中的任何其他格式/注释/等。