C # How can I get each type and length of a column and then use the length for padright to get spaces at the end of each field

I have a console application that extracts data from an SQL table into a flat file. How can I get each type and length of a column and then use the length of each column for padright (length) to get spaces at the end of each field. Here is what I have right now when this feature is not enabled.

thanks

{ var destination = args[0]; var command = string.Format("Select * from {0}", Validator.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].ToString().PadRight(513)); writer.WriteLine(); } writer.Close(); } 
+4
source share
2 answers

IDataReader offers the GetSchemaTable () method , which provides the ColumnSize attribute (it depends on the main provider - the version of SQL Server is here ).

+7
source

You can use the DataReader GetSchemaTable method to retrieve column schema information. This article has complete information about obtaining metadata about the received data.

Once you have the column size, you can add trailing characters to the extracted data using the String.PadRight method.

+3
source

Source: https://habr.com/ru/post/1311774/


All Articles