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}");
}
}