我有一个固定长度字段,我想在其中显示路径信息。我认为在 .NET 中,有一种方法可以通过插入省略号来缩写长路径名以适合固定长度字段,例如“.. ....\myfile.txt”。我一辈子都找不到这个方法。
最佳答案
使用 TextRenderer
显示缩写路径。 MeasureText
我和OP有同样的困境,因为我需要一个解决方案来显示缩写路径,而不需要太多麻烦,以便我的UI可以轻松显示路径的主要部分。最终解决方案:使用TextRenderer
的MeasureText
方法如下:
public static string GetCompactedString(
string stringToCompact, Font font, int maxWidth)
{
// Copy the string passed in since this string will be
// modified in the TextRenderer's MeasureText method
string compactedString = string.Copy(stringToCompact);
var maxSize = new Size(maxWidth, 0);
var formattingOptions = TextFormatFlags.PathEllipsis
| TextFormatFlags.ModifyString;
TextRenderer.MeasureText(compactedString, font, maxSize, formattingOptions);
return compactedString;
}
重要提示:传入格式选项 TextFormatFlags.ModifyString
实际上导致MeasureText
方法将字符串参数 (compactedString
) 更改为压缩字符串。这看起来很奇怪,因为没有指定显式的 ref 或 out 方法参数关键字并且字符串是不可变的。然而,情况确实如此。我假设字符串的指针已通过不安全代码更新为新的压缩字符串。
作为另一个出租人注释,由于我希望压缩字符串来压缩路径,因此我还使用了 TextFormatFlags.PathEllipsis
格式选项。
我发现在控件上创建一个小的扩展方法很方便,以便任何控件(如 TextBox 和 Label )都可以将其文本设置为压缩路径:
public static void SetTextAsCompactedPath(this Control control, string path)
{
control.Text = GetCompactedString(path, control.Font, control.Width);
}
压缩路径的替代方法:
有一些自行开发的紧凑路径解决方案以及一些可以使用的 WinApi 调用。
PathCompactPathEx - 根据所需的字符串长度(以字符为单位)压缩字符串
您可以使用pinvoke调用PathCompactPathEx
根据您希望限制的字符数来压缩字符串。请注意,这没有考虑字体以及字符串在屏幕上显示的宽度。
代码来源 PInvoke:http://www.pinvoke.net/default.aspx/shlwapi.pathcompactpathex
[DllImport("shlwapi.dll", CharSet=CharSet.Auto)]
static extern bool PathCompactPathEx(
[Out] StringBuilder pszOut, string szPath, int cchMax, int dwFlags);
public static string CompactPath(string longPathName, int wantedLength)
{
// NOTE: You need to create the builder with the
// required capacity before calling function.
// See http://msdn.microsoft.com/en-us/library/aa446536.aspx
StringBuilder sb = new StringBuilder(wantedLength + 1);
PathCompactPathEx(sb, longPathName, wantedLength + 1, 0);
return sb.ToString();
}
其他解决方案
还有更多解决方案,涉及正则表达式和智能路径解析以确定省略号的位置。这是我看到的一些:
关于.net - 如何在 .NET 中显示缩写路径名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1764204/