How can I truncate my strings with a "..." if they are too long?

Here is the logic wrapped up in an extension method:

public static string Truncate(this string value, int maxChars)
{
    return value.Length <= maxChars ? value : value.Substring(0, maxChars) + "...";
}

Usage:

var s = "abcdefg";

Console.WriteLine(s.Truncate(3));

All very good answers, but to clean it up just a little, if your strings are sentences, don't break your string in the middle of a word.

private string TruncateForDisplay(this string value, int length)
{
  if (string.IsNullOrEmpty(value)) return string.Empty;
  var returnValue = value;
  if (value.Length > length)
  {
    var tmp = value.Substring(0, length) ;
    if (tmp.LastIndexOf(' ') > 0)
       returnValue = tmp.Substring(0, tmp.LastIndexOf(' ') ) + " ...";
  }                
  return returnValue;
}

Tags:

C#

String