Fixed Length String Extension

// December 9th, 2009 // Useful Code

This little snippet is great for exporting a field to a fixed length file. It will pad a string to X length using spaces and will extend any string object.

//Code


        /// <summary>
        /// CREATE A FIXED LENGTH STRING FOR INSERTING INTO FIXED LENGTH FILES OR GRIDS
        /// </summary>
        /// <param name="s">STRING TO BE PADDED</param>
        /// <param name="length">LENGTH OF FINAL STRING</param>
        /// <returns>FIXED LENGTH STRING OF X LENGTH</returns>
        public static string FixedLengthString(this string s, int length)
        {
            //IF THE STRING IS ALREADY LONG ENOUGH THEN JUST RETURN S
            //ELSE ADD SPACES TO THE END TO MAKE THE STRING X LENGTH
            if (s.Length >= length)
                return s;
            else
                return string.Concat(s, new string(' ', length - s.Length));
        }
Be Sociable, Share!
  • RSS
  • Twitter
  • Facebook
  • LinkedIn
  • DeviantArt