English 中文(简体)
• 如何展示缩略语。 NET
原标题:How to display abbreviated path names in .NET

我有一个固定的透镜,我想展示道路信息。 我深思。 NET采用一种方法,通过添加“......myfile.txt”等词句,将长途地名缩为固定长处。 我会发现这种方法。

问题回答

Display Abbreviated Paths using TextRenderer.MeasureText

我的两难处境与禁止化学武器组织一样,因为我需要找到一种解决办法,在没有太多的通道的情况下展示一条温和的道路,以便我方能轻易地展示一条道路的主要部分。 最终解决办法:使用TextRenderer sMeasureT>ext><><><>> 类似方法:

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

<>Important: http://msdn.microsoft.com/en-us/library/system.windows.forms.textformatflags.aspx”rel=“noreferer”TextFormatFlags.ModificationString 实际原因如下: 代码>MeasureText 改变扼杀性论点的方法(compactedString)成为一条有条理的扼杀。 这一点似乎很受欢迎,因为没有明确的<代码>ref或out方法参数关键词被具体指明,而且说明是不可更改的。 然而,这无疑是事实。 我假定,通过不安全的法典对新的紧凑的扼杀进行了更新。

作为另一个较次要的注解,因为我想要紧凑地铺一条路,我还使用了TextFormatFlags.PathEllipsis 格式选择。

我认为,在控制上采用一种小的延伸方法,以便任何控制(如文本Box和Label s)能够将其案文置于一条有节制的道路:

public static void SetTextAsCompactedPath(this Control control, string path)
{
   control.Text = GetCompactedString(path, control.Font, control.Width);
}

Alternative Ways to Compact a Path:

有家庭种植的紧凑道路解决方案以及一些WinApi电话可以使用。

PathCompactPathEx - Compacting a String Based on Desired String Length in Characters

http://www.pinvoke.net/default.aspx/shlwapi.pathcompactpathex”rel=“noretinger”PathCompactPathEx。 请注意,这并不考虑字句的字面和深度。

资料来源:PInvoke:

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

Other Solutions

那里还有更多的解决办法,包括定期表达和铺平道路,以确定什么地方放下lip。 我看到:

在此情况下,有人正在寻找同样的东西。 我担任这一职务:

/// <summary>
/// Shortens a file path to the specified length
/// </summary>
/// <param name="path">The file path to shorten</param>
/// <param name="maxLength">The max length of the output path (including the ellipsis if inserted)</param>
/// <returns>The path with some of the middle directory paths replaced with an ellipsis (or the entire path if it is already shorter than maxLength)</returns>
/// <remarks>
/// Shortens the path by removing some of the "middle directories" in the path and inserting an ellipsis. If the filename and root path (drive letter or UNC server name)     in itself exceeds the maxLength, the filename will be cut to fit.
/// UNC-paths and relative paths are also supported.
/// The inserted ellipsis is not a true ellipsis char, but a string of three dots.
/// </remarks>
/// <example>
/// ShortenPath(@"c:websitesmyprojectwww_myprojApp_Data	hemegafile.txt", 50)
/// Result: "c:websitesmyproject...App_Data	hemegafile.txt"
/// 
/// ShortenPath(@"c:websitesmyprojectwww_myprojApp_Data	heextremelylongfilename_morelength.txt", 30)
/// Result: "c:...gfilename_morelength.txt"
/// 
/// ShortenPath(@"\myserver	hesharemyprojectwww_myprojApp_Data	heextremelylongfilename_morelength.txt", 30)
/// Result: "\myserver...e_morelength.txt"
/// 
/// ShortenPath(@"\myserver	hesharemyprojectwww_myprojApp_Data	hemegafile.txt", 50)
/// Result: "\myserver	heshare...App_Data	hemegafile.txt"
/// 
/// ShortenPath(@"\192.168.1.178	hesharemyprojectwww_myprojApp_Data	hemegafile.txt", 50)
/// Result: "\192.168.1.178	heshare...	hemegafile.txt"
/// 
/// ShortenPath(@"	hesharemyprojectwww_myprojApp_Data", 30)
/// Result: "	heshare...App_Data"
/// 
/// ShortenPath(@"	hesharemyprojectwww_myprojApp_Data	hemegafile.txt", 35)
/// Result: "	heshare...	hemegafile.txt"
/// </example>
public static string ShortenPath(string path, int maxLength)
{
    string ellipsisChars = "...";
    char dirSeperatorChar = Path.DirectorySeparatorChar;
    string directorySeperator = dirSeperatorChar.ToString();

    //simple guards
    if (path.Length <= maxLength)
    {
        return path;
    }
    int ellipsisLength = ellipsisChars.Length;
    if (maxLength <= ellipsisLength)
    {
        return ellipsisChars;
    }


    //alternate between taking a section from the start (firstPart) or the path and the end (lastPart)
    bool isFirstPartsTurn = true; //drive letter has first priority, so start with that and see what else there is room for

    //vars for accumulating the first and last parts of the final shortened path
    string firstPart = "";
    string lastPart = "";
    //keeping track of how many first/last parts have already been added to the shortened path
    int firstPartsUsed = 0;
    int lastPartsUsed = 0;

    string[] pathParts = path.Split(dirSeperatorChar);
    for (int i = 0; i < pathParts.Length; i++)
    {
        if (isFirstPartsTurn)
        {
            string partToAdd = pathParts[firstPartsUsed] + directorySeperator;
            if ((firstPart.Length + lastPart.Length + partToAdd.Length + ellipsisLength) > maxLength)
            {
                break;
            }
            firstPart = firstPart + partToAdd;
            if (partToAdd == directorySeperator)
            {
                //this is most likely the first part of and UNC or relative path 
                //do not switch to lastpart, as these are not "true" directory seperators
                //otherwise "\myserver	heshareoutprojectwww_projectfile.txt" becomes "\...www_projectfile.txt" instead of the intended "\myserver...file.txt")
            }
            else
            {
                isFirstPartsTurn = false;
            }
            firstPartsUsed++;
        }
        else
        {
            int index = pathParts.Length - lastPartsUsed - 1; //-1 because of length vs. zero-based indexing
            string partToAdd = directorySeperator + pathParts[index];
            if ((firstPart.Length + lastPart.Length + partToAdd.Length + ellipsisLength) > maxLength)
            {
                break;
            }
            lastPart = partToAdd + lastPart;
            if (partToAdd == directorySeperator)
            {
                //this is most likely the last part of a relative path (e.g. "websitesmyprojectwww_myprojApp_Data")
                //do not proceed to processing firstPart yet
            }
            else
            {
                isFirstPartsTurn = true;
            }
            lastPartsUsed++;
        }
    }

    if (lastPart == "")
    {
        //the filename (and root path) in itself was longer than maxLength, shorten it
        lastPart = pathParts[pathParts.Length - 1];//"pathParts[pathParts.Length -1]" is the equivalent of "Path.GetFileName(pathToShorten)"
        lastPart = lastPart.Substring(lastPart.Length + ellipsisLength + firstPart.Length - maxLength, maxLength - ellipsisLength - firstPart.Length);
    }

    return firstPart + ellipsisChars + lastPart;
}

rel=“nofollow noretinger”>Originial post with (a Little) background here

http://blog.codinghorror.com/shortening-long-file-paths/“rel=”nofollow noreferer”>Coding Horror blog post on shorting long file paths There sWindows AP calls PathCompCathPathtPatht/<> 你可以使用。

页: 1 然而,Net本身没有能够回归一条三重道路的方法。

我不知道自动这样做的方法,但你可以很容易地制造一种方法,即要么使用Substring()和最后IndexOf(“”),要么使用该系统。

如何:

string longPath = @"c:somewheremyfile.txt";
string shortPath = @".." + Path.GetFileName(longPath);

我发现,从文本Box中得出的一个易于使用的类别如下:。 EllipsisTextBox , encapsulates StringTriming。 EllipsisPath。 我的工作!





相关问题
Manually implementing high performance algorithms in .NET

As a learning experience I recently tried implementing Quicksort with 3 way partitioning in C#. Apart from needing to add an extra range check on the left/right variables before the recursive call, ...

Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How do I compare two decimals to 10 decimal places?

I m using decimal type (.net), and I want to see if two numbers are equal. But I only want to be accurate to 10 decimal places. For example take these three numbers. I want them all to be equal. 0....

Exception practices when creating a SynchronizationContext?

I m creating an STA version of the SynchronizationContext for use in Windows Workflow 4.0. I m wondering what to do about exceptions when Post-ing callbacks. The SynchronizationContext can be used ...

Show running instance in single instance application

I am building an application with C#. I managed to turn this into a single instance application by checking if the same process is already running. Process[] pname = Process.GetProcessesByName("...

How to combine DataTrigger and EventTrigger?

NOTE I have asked the related question (with an accepted answer): How to combine DataTrigger and Trigger? I think I need to combine an EventTrigger and a DataTrigger to achieve what I m after: when ...