Reputation: 2256
I have the following values
A = 1,
B = (NULL of 7 characters),
C = denimRocks ,
D = Yes789,
E = (NULL of 2 characters),
F = ATR.
I want to write these to a line of a textfile with A starting at position 1 of the line.B starting at position 2, C at position 8 and so on.
I want to show blank spaces for the nulls. I tried using streamwriter but I cant get to acheive what I want to do.
Help please.
Upvotes: 2
Views: 9564
Reputation: 800
Try like this:
string a=string.Empty;
StreamWriter yourStream = null;
protected void Page_Load(object sender, EventArgs e)
{
yourStream = File.CreateText("D:\\test1.txt"); // creating file
a = String.Format("|{0,1}|{1,2}|{2,7}|......", "A", "B", "",......); //formatting text based on poeition
yourStream.Write(a+"\r\n");
yourStream.Close();
}
Upvotes: 4
Reputation: 216243
string.Format and the composite formatting rules allow to align a string exactly as you wish:
string A = "1";
string B = "";
string C = "denimRocks";
string D = "yes789"
string E = "";
string F = "ATR";
string result = string.Format("{0}{1,7}{2,10}{3,6}{4,2}{5,3}", A,B,C,D,E,F);
Console.WriteLine(result);
In this way you get every piece of information aligned exactly in the spaces reserved for them and writing to a file is just a matter to open the appropriate stream and write the resulting string
Upvotes: 0