Display path in shortcut

Are there any automatic methods for trimming a path string in .NET?

For example:

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

becomes

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

It would be especially great if it were built into the Label class, and I seem to remember that it is - I cannot find it, though!

+6
c # path winforms
source share
5 answers

Use TextRenderer.DrawText with the TextFormatFlags.PathEllipsis flag

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

Your code there is 95%. The only problem is that the cropped text is at the top of the text, which is already on the label.

Yes, thanks, I knew about that. My intention was to demonstrate the use of the DrawText method. I did not know if you want to manually create an event for each label or simply override the OnPaint() method in the inherited label. Thank you for sharing your final decision.

+9
source share

It’s not difficult to write yourself:

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

I think you can even add it as an extension method.

+3
source share

@ lubos hasko Your code here is 95%. The only problem is that the cropped text is drawn on top of the text that is already on the label. This is easy to solve:

  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); 
+3
source share

What you think on the label is that it will be ... if it is longer than the width (not set for automatic size), but it will

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

If there is support, it will probably be in the Path class in System.IO

0
source share

You can use the System.IO.Path.GetFileName method and add this line to the shortened line System.IO.Path.GetDirectoryName.

0
source share

All Articles