Avatar of rwheeler23
rwheeler23
Flag for United States of America

asked on 

C# and proper way to write a fixed width format using a dataset.

I need to direct output to a text in a fixed width format.  The data is sitting in a dataset which i convert to a datatable. The problem I have is that I want columns to position that are a multiple of 40. I thought this line would do it:

                                line = line + row[column].ToString().PadRight(40 - row[column].ToString().Length, ' ');

However, what i have discovered is that     row[column].ToString().Length, ' '); will strip away the blanks at the end when it computes the length. Is there a directive that will not do that? What is the proper way to accomplish this?

                using (StreamWriter outfile = new System.IO.StreamWriter(@"C:\output.txt"))
                foreach (DataTable table in DataSet.Tables)
                {
                    foreach (DataRow row in table.Rows)                      
                    {
                        Model.line = "";
                        foreach (DataColumn column in table.Columns)
                        {
                                line = line + row[column].ToString().PadRight(40 - row[column].ToString().Length, ' ');
                        }
                            outfile.WriteLine(Model.line);
                    }
                }
C#

Avatar of undefined
Last Comment
rwheeler23

8/22/2022 - Mon