格式化.csproj文件的工具



是否有一个选项,在Visual Studio或工具(VS插件?)自动格式化.csproj文件,如果他们弄乱后,例如:合并冲突解决方案?最好采用Visual Studio创建它们时的格式。也许在ReSharper中有一个我不知道的选项?

我尝试了命令行工具organize-csproj,但它有一系列不便-需要。net Core 3.1运行时安装,在输出.csproj中添加注释,在顶部添加XML声明,并且不像VS那样在每个主要元素(PropertyGroup或ItemGroup之后)之后插入额外的换行符。它的配置似乎也不允许我改变这种行为。

您可以为.editorconfig文件中的其他文件指定格式选项(例如标识)。VS通常会遵守这些规则。例如,我有

[*.{csproj}]
charset = utf-8-bom
indent_style = space
indent_size = 2
tab_width = 2

(与。cs文件相反,其中indent_size通常为4)

您可以使用以下方法在XML级别上美化任何XML文件:

static void XmlFormat(string inFileName, string outFileName, 
bool _NewLineOnAttributes, 
string _IndentChars, 
bool _OmitXmlDeclaration)
{
try
{  
//  adjust Encoding, if necessary
TextReader rd = new StreamReader(inFileName, Encoding.Default);
XmlDocument doc = new XmlDocument();
doc.Load(rd);
if (rd != Console.In)
{
rd.Close();
}
//  adjust Encoding if necessary
var wr = new StreamWriter(outFileName, false, Encoding.Default);
//  https://docs.microsoft.com/en-us/dotnet/api/system.xml.xmlwritersettings?view=net-5.0
var settings =
new XmlWriterSettings 
{ 
Indent = true, 
IndentChars = _IndentChars,
NewLineOnAttributes = _NewLineOnAttributes,
OmitXmlDeclaration = _OmitXmlDeclaration
};
using (var writer = XmlWriter.Create(wr, settings))
{
doc.WriteContentTo(writer);
}
}
catch (Exception ex)
{
Console.WriteLine($"Error formatting {inFileName}: {ex.Message}");
}
}

最新更新