.net - 如何在 .NET 中显示缩写路径名

标签 .net path filenames

我有一个固定长度字段,我想在其中显示路径信息。我认为在 .NET 中,有一种方法可以通过插入省略号来缩写长路径名以适合固定长度字段,例如“.. ....\myfile.txt”。我一辈子都找不到这个方法。

最佳答案

使用 TextRenderer 显示缩写路径。 MeasureText

我和OP有同样的困境,因为我需要一个解决方案来显示缩写路径,而不需要太多麻烦,以便我的UI可以轻松显示路径的主要部分。最终解决方案:使用TextRendererMeasureText方法如下:

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/

相关文章:

c# - 使用 sshnet 执行 unix 脚本

c# - 如何用伪造的值表示可为空的值?

path - 带有绝对路径的 FileNotFoundException

c# - 文件名匹配 "..\ThirdParty\dlls\*.dll"

.net - 将 png 缩小到比原来大的大小

.net - 在哪里检查对象是否为空?

python-2.7 - 错误 : Problem: conflicting requests - nothing provides/usr/bin/python needed by python-chardet in CentOS 8

c# - Process.Start() 和 PATH 环境变量

java - 在调用approveSelection()之前修改或执行JFileChooser保存对话框文件名

windows - Git pull 错误 : unable to create file (Invalid argument)