C# how to get trailing spaces from the end of a varchar(513) field while exporting SQL table to a flat file
How do I get empty spaces from the end of a varchar(513) field while exporting data from SQL table to a flat file. I have a console application. Here is what I am using to export a SQL table having only one column of varchar(513) to a flat file. But I need to get all the 513 characters including spaces at the end. How do I change this code to incorporate that.
Thanks
{
var destination = args[0];
var command = string.Format("Select * from {0}", Valida开发者_StackOverflow社区tor.Check(args[1]));
var connectionstring = string.Format("Data Source={0}; Initial Catalog=dbname;Integrated Security=SSPI;", args[2]);
var helper = new SqlHelper(command, CommandType.Text, connectionstring);
using (StreamWriter writer = new StreamWriter(destination))
using (IDataReader reader = helper.ExecuteReader())
{
while (reader.Read())
{
Object[] values = new Object[reader.FieldCount];
int fieldCount = reader.GetValues(values);
for (int i = 0; i < fieldCount; i++)
writer.Write(values[i]);
writer.WriteLine();
}
writer.Close();
}
Contrary to char and nchar which have fixed size and padding spaces at the end, vchar and nvarchar don't. However you can use the String.PadRight()
function to achieve the same result:
writer.Write(values[i].ToString().PadRight(513));
writer.Write{"{0,-513}", values[i])
Replace -513 with 513 if the space is padded on the left rather than on the right, I never seem to remember which one works :-)
精彩评论