2
我正在嘗試更新我的文件中的一個語句。我的要求是使用roslyn替換語句
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); }
聲明從左邊開始,甚至開始「}」brac ket出現在同一條線上。 有什麼建議嗎?