Click here to Skip to main content
15,919,879 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to add spaces to a dynamic string in a string builder for a specific length field in asp.net with c#

Here the string is dynamic and it will be of some length less than the specified length and I need to add spaces up to that specified length.

What I have tried:

C#
sbOAKAccp.Append("01");//Record Type
sbOAKAccp.Append("03");//Standard Level
sbOAKAccp.Append(dsXml.Tables["EHR_M01"].Rows[0]["TestFileIndicator"].ToString());//Test Field Indicator
sbOAKAccp.Append(dsXml.Tables["EHR_M01"].Rows[0]["DestinationRoutingNumber"].ToString());//Destination Routing Number
sbOAKAccp.Append(strFileName);//OCE/RCE Filename
sbOAKAccp.Append(dsXml.Tables["EHR_M01"].Rows[0]["FileCreationDate"].ToString());//File Creation Date
sbOAKAccp.Append(dsXml.Tables["EHR_M01"].Rows[0]["FileCreationTime"].ToString());//File Creation Time
sbOAKAccp.Append("N");//Resend Indicator
sbOAKAccp.Append(71);//ECE Type
sbOAKAccp.Append("01");//ECE Status Code(Reject-99)
sbOAKAccp.Append("Accepted with exceptions".PadRight(29, ' '));//Collection Status Description
sbOAKAccp.Append(Environment.NewLine);
Posted
Updated 20-Jan-17 11:13am
v3
Comments
[no name] 20-Jan-17 8:10am    
https://msdn.microsoft.com/en-us/library/66f6d830(v=vs.110).aspx

1 solution


Controlling spacing
You can define the width of the string that is inserted into the result string by using syntax such as {0,12}, which inserts a 12-character string. In this case, the string representation of the first object is right-aligned in the 12-character field. (If the string representation of the first object is more than 12 characters in length, though, the preferred field width is ignored, and the entire string is inserted into the result string.)

Controlling alignment
By default, strings are right-aligned within their field if you specify a field width. To left-align strings in a field, you preface the field width with a negative sign, such as {0,-12} to define a 12-character right-aligned field.

For example, to pad the destination routing number to 10 characters, with the spaces at the end:
sbOAKAccp.AppendFormat("{0,-10}", dsXml.Tables["EHR_M01"].Rows[0]["DestinationRoutingNumber"]);

To pad the filename to 30 characters, with the spaces at the start:
sbOAKAccp.Append("{0,30}", strFileName);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900