How to truncate or pad a string to a fixed length in c#

All you need is PadRight followed by Substring (providing that source is not null):

string source = ...
int length = 5;

string result = source.PadRight(length).Substring(0, length);

In case source can be null:

string result = source == null 
  ? new string(' ', length) 
  : source.PadRight(length).Substring(0, length);

private string fixedLength(string input, int length){
    if(input.Length > length)
        return input.Substring(0,length);
    else
        return input.PadRight(length, ' ');
}

Tags:

C#

String