Reputation: 1188
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?
Upvotes: 4
Views: 21663
Reputation: 4492
I think you can use PadRight or PadLeft function for this.
string _line = item.FirstName.PadRight(20) + item.Number.PadRight(20) + item.State.PadRight(20) + item.Zip.PadRight(20);
file.WriteLine(_line);
Upvotes: 1
Reputation: 1596
Firstly, use string.Format, rather than concatenation:
int lineCount = File.ReadAllLines(Path.Combine(directory.LocalDirectory, file.Name)).Length.ToString();
string message = string.Format("{0}. {1}\t Record Count: " {2}\n", (index + 1), file.Name, lineCount);
To answer your question, you can align text within a formatted string using the following syntax:
string message = string.Format("{0}. {1,-10}\t Record Count: " {2}\n", (index + 1), file.Name, lineCount);
The additional -10 will ensure that the inserted text is left-padded to 10 characters.
Upvotes: 3
Reputation: 311
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.
Upvotes: 5
Reputation: 484
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.
Upvotes: 4