Created
June 25, 2013 13:20
-
-
Save iburlakov/5858369 to your computer and use it in GitHub Desktop.
Ellipsis path by replacing path parts with some ellipsis const, ... in this particular case.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.IO; | |
using System.Linq; | |
using System.Windows.Data; | |
namespace Converters | |
{ | |
public class PathEllipsisConverter : IValueConverter | |
{ | |
private const string EllipsisChars = "..."; | |
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) | |
{ | |
if (targetType != typeof(string)) | |
{ | |
throw new InvalidOperationException("The target must be a string"); | |
} | |
// check that value is path | |
try | |
{ | |
Path.GetFullPath(value as string); | |
} | |
catch | |
{ | |
throw new InvalidOperationException("The value must be a valid windows path"); | |
} | |
// check that parameter is integer | |
int maxLength; | |
if (!int.TryParse(parameter.ToString(), out maxLength) || maxLength == 0) | |
{ | |
throw new InvalidOperationException("The paramente must be a integer"); | |
} | |
var path = value as string; | |
if (path.Length <= maxLength) | |
{ | |
return path; | |
} | |
var parts = path.Split(Path.DirectorySeparatorChar).ToList(); | |
var filenane = parts.Last(); | |
parts.RemoveAt(parts.Count - 1); | |
var ellipsedValue = string.Empty; | |
do | |
{ | |
if (parts.Count > 0) | |
{ | |
parts.RemoveAt(parts.Count - 1); | |
} | |
ellipsedValue = string.Join(Path.DirectorySeparatorChar.ToString(), | |
parts.Concat(new string[] { EllipsisChars, filenane })); | |
} while (ellipsedValue.Length > maxLength && parts.Count > 0); | |
return ellipsedValue; | |
} | |
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) | |
{ | |
if (targetType != typeof(string)) | |
{ | |
throw new InvalidOperationException("The target must be a string"); | |
} | |
return value; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment