title: How can I format a string into a fixed width field in .Net?
body: <p>I am trying to format a string of arbitrary length into a fixed width field for display.  </p>
  
  <p>Let's use a width of 20 as an example, and call the string to be formatted s.  I'm adding the formatted string to a StringBuilder named b.</p>
  
  <pre><code>Dim b As New System.Text.StringBuilder()
  Dim s as New String
  </code></pre>
  
  <p>If the string I want to display is shorter than 20 characters, I can do this:</p>
  
  <pre><code>b.Append(s.PadRight(20))
  </code></pre>
  
  <p>or</p>
  
  <pre><code>b.AppendFormat("{0,-20}", s)
  </code></pre>
  
  <p>So far, so good.  But, if the string is longer than 20 characters, I want the string to be truncated to 20 characters as it is appended.  The code above appends the entire string.</p>
  
  <p>I tried this:</p>
  
  <pre><code>b.Append(s.Substring(0,20).PadRight(20))
  </code></pre>
  
  <p>But, this fires an exception if the string was shorter than 20 characters.</p>
  
  <p>So, I ended up with: </p>
  
  <pre><code>b.Append(s.PadRight(20).Substring(0,20))
  </code></pre>
  
  <p>This seems to do the job.  The PadRight prevents the exception by making sure thet string has 20 characters before the Substring is performed.</p>
  
  <p>I was wondering if there is an alternate method that would look more elegant and avoid padding the string just so prevent the substring from causing an exception.  Have I missed a feature of String.Format that can accomplish this in one step?</p>
  
  <p><strong>Edited to add solution:</strong></p>
  
  <p>I ended up with the following code:</p>
  
  <pre><code>Module Extensions
      &lt;Extension()&gt; _
      Function AppendFixed(ByVal b As StringBuilder, ByVal s As String, ByVal width As Integer) As StringBuilder
          If s.Length &gt;= width Then
              b.Append(s, 0, width)
          Else
              b.Append(s)
              b.Append(" ", width - s.Length)
          End If
          Return b
      End Function
  End Module
  </code></pre>
  
  <p>This uses an extension method to clean up the syntax, as suggested by Joel and Merlyn, and uses the StringBulider Append overloads to avoid creating new strings that will have to be garbage collected, as suggested by supercat.  Thanks to those that helped.</p>