标签中的路径显示

是否有任何自动方法可以在.NET中修剪路径字符串?

例如:

C:\Documents and Settings\nick\My Documents\Tests\demo data\demo data.emx 

 C:\Documents...\demo data.emx 

如果它被内置到Label类中会特别酷,我似乎记得它 – 但是找不到它!

TextRenderer.DrawTextTextFormatFlags.PathEllipsis标志一起使用

 void label_Paint(object sender, PaintEventArgs e) { Label label = (Label)sender; TextRenderer.DrawText(e.Graphics, label.Text, label.Font, label.ClientRectangle, label.ForeColor, TextFormatFlags.PathEllipsis); } 

你的代码是95%。 唯一的问题是修剪的文本绘制在标签上已经存在的文本的顶部。

是的,谢谢,我知道这一点。 我的目的只是为了演示使用DrawText方法。 我不知道您是否要为每个标签手动创建事件,或者只是重写inheritance标签中的OnPaint()方法。 感谢您分享您的最终解决方案。

虽然不难写自己:

  public static string TrimPath(string path) { int someArbitaryNumber = 10; string directory = Path.GetDirectoryName(path); string fileName = Path.GetFileName(path); if (directory.Length > someArbitaryNumber) { return String.Format(@"{0}...\{1}", directory.Substring(0, someArbitaryNumber), fileName); } else { return path; } } 

我想你甚至可以将它添加为扩展方法。

@ lubos hasko你的代码是95%。 唯一的问题是修剪的文本绘制在标签上已经存在的文本的顶部。 这很容易解决:

  Label label = (Label)sender; using (SolidBrush b = new SolidBrush(label.BackColor)) e.Graphics.FillRectangle(b, label.ClientRectangle); TextRenderer.DrawText( e.Graphics, label.Text, label.Font, label.ClientRectangle, label.ForeColor, TextFormatFlags.PathEllipsis); 

你在标签上的想法是它会放…如果它比宽度长(不设置为自动尺寸),但那将是

 c:\Documents and Settings\nick\My Doc... 

如果有支持,它可能会在System.IO中的Path类上

您可以使用System.IO.Path.GetFileName方法并将该字符串附加到缩短的System.IO.Path.GetDirectoryName字符串。