Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format a string with fixed width fields

I'm was wondering if there is a way to format a string to format a string, what I mean is, I have a foreach loop that get a information from some files and how many records has each file, as the length of each file is different the format is change.

My example is, I have 3 files:

 1.- MyFile1.txt   RecordCount: 5
 2.- anotherfile.txt    RecordCount: 8
 3.- MyTestFile.doc   RecordCount: 17

As you can see are not formated, I want something like this:

 1.- MyFile1.txt        RecordCount: 5
 2.- anotherfile.txt    RecordCount: 8
 3.- MyTestFile.doc     RecordCount: 17

does not matter the length of the file, RecordCount will be in the same place.

What I have is this:

 foreach (RemoteFileInfo file in MySession.EnumerateRemoteFiles(directory.RemoteDirectory, directory.RemoteFiles, EnumerationOptions.None))
 {
     BodyMessage.Append((index + 1) + ". " + file.Name + "        Record Count: " + File.ReadAllLines(Path.Combine(directory.LocalDirectory, file.Name)).Length.ToString() + "\n");
     index++;
 }

Any idea?

like image 964
Javier Salas Avatar asked Oct 26 '25 10:10

Javier Salas


2 Answers

foreach (RemoteFileInfo file in MySession.EnumerateRemoteFiles(directory.RemoteDirectory, directory.RemoteFiles, EnumerationOptions.None))
{
    int lines= File.ReadAllLines(Path.Combine(directory.LocalDirectory, file.Name)).Length.ToString();
    string appending = String.Format("{0,2}.- {1,-18} RecordCount: {3}", file.Name, lines);
    BodyMessage.Append(appending);
    index++;
}

See MSDN: String.Format Method.

like image 149
soumasandesu Avatar answered Oct 27 '25 23:10

soumasandesu


You can try using \t in your strings which will insert a tab or you can try padding each portion so they always take up the same amount space.

For example:

string fileName = file.Name.PadRight(50);

will ensure that the string fileName is at least 50 characters long. I say at least because you could always have a file name that is larger than 50 characters.

like image 34
Tyler Avatar answered Oct 28 '25 00:10

Tyler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!