Path Display in Label

会有一股神秘感。 提交于 2020-01-02 03:55:23

问题


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 particularly cool if this were built into the Label class, and I seem to recall it is--can't find it though!


回答1:


Use TextRenderer.DrawText with 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 is 95% there. The only problem is that the trimmed text is drawn on top of the text which is already on the label.

Yes thanks, I was aware of that. My intention was only to demonstrate use of DrawText method. I didn't know whether you want to manually create event for each label or just override OnPaint() method in inherited label. Thanks for sharing your final solution though.




回答2:


@ lubos hasko Your code is 95% there. The only problem is that the trimmed text is drawn on top of the text which is already on the label. This is easily solved:

    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:


Not hard to write yourself though:

    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 guess you could even add it as an extension method.




回答4:


What you are thinking on the label is that it will put ... if it is longer than the width (not set to auto size), but that would be

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

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




回答5:


You could use the System.IO.Path.GetFileName method and append that string to a shortened System.IO.Path.GetDirectoryName string.



来源:https://stackoverflow.com/questions/20467/path-display-in-label

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!