File tree Expand file tree Collapse file tree 1 file changed +15
-1
lines changed
src/PackageReferenceCleaner Expand file tree Collapse file tree 1 file changed +15
-1
lines changed Original file line number Diff line number Diff line change 11using System . Collections . Immutable ;
22using System . IO ;
33using System . Linq ;
4+ using System . Xml ;
45using System . Xml . Linq ;
56using Microsoft . CodeAnalysis ;
67using Microsoft . CodeAnalysis . Diagnostics ;
@@ -58,8 +59,21 @@ public override void Initialize(AnalysisContext context)
5859 if ( cleaned > 0 )
5960 {
6061 ctx . ReportDiagnostic ( Diagnostic . Create ( SupportedDiagnostics [ 0 ] , null , cleaned ) ) ;
61- doc . Save ( projectFile ) ;
62+ // Detect whether the file originally had an XML declaration or not.
63+ var hasDecl = HasXmlDeclaration ( projectFile ! ) ;
64+ // Save emits the XML declaration, but ToString doesn't.
65+ if ( hasDecl )
66+ doc . Save ( projectFile ) ;
67+ else
68+ File . WriteAllText ( projectFile , doc . ToString ( ) . Trim ( ) ) ;
6269 }
6370 } ) ;
6471 }
72+
73+ static bool HasXmlDeclaration ( string projectFile )
74+ {
75+ using var reader = new StreamReader ( projectFile ) ;
76+ using var xml = XmlReader . Create ( reader ) ;
77+ return xml . Read ( ) && xml . NodeType == XmlNodeType . XmlDeclaration ;
78+ }
6579}
You can’t perform that action at this time.
0 commit comments