开发者

Writing to a text file at specific position?

How to write a file in a specific position instead of giving space like " ".Here i am writing to a file,the output i am getting is like

TIMESTAMP              'ATRS_ACCT_TIMESTAMP',
OU_ID              'ATRS_ACCT_OU_ID',
COMPANY_CODE              'ATRS_ACCT_COMPANY_CODE',
BU_ID              'ATRS_ACCT_BU_ID',

but i need output like this

TIMESTAMP          'ATRS_ACCT_TIMESTAMP',
OU_ID              'ATRS_ACCT_OU_ID',
COMPANY_CODE       'ATRS_ACCT_COMPANY_CODE',
BU_ID              'ATRS_ACCT_BU_ID',

Here is my code

string[] ss = new string[tblSchema.Rows.Count];
for (int i = 0; i < tblSchema.Rows.Count; i++)
{
    ss[i] = (tblSchema.Rows[i]["ColumnName"].ToString());
    dest.WriteLine(ss开发者_如何学运维[i].ToUpper() + "              " + 
                   "'" + textBox2.Text + ss[i].ToUpper() + "'" + ",");
}

Any suggestion?


Use String.Format() and specify the field length for your fields. Something like this:

var line = String.Format("{0,-20} '{1}{0}',", ss[i].ToUpper(), textBox2.Text);
// "{0,-20}" - Print the first item using a minimum of 20 characters left aligned
dest.WriteLine(line);


Maybe this helps for understanding:

    string txt = "Hello World";
    string txt2 = "Test";
    string txt3 = "Let's go";

    string line = String.Format("{0,-15} {1,-10} {2,10}", txt, txt2, txt3);

    Console.WriteLine(line);
    Console.ReadLine();

Explanation:

This will position the text between position 0-15 left aligned:

{0,-15} = First string [txt], 1 = Text, -15 = amount of characters allowed for the string, - = left align

This will position the text between position 16-26 right aligned:

{1, 10} = Second string [txt2], 1 = Text, 10 = amount of characters allowed for the string, right align

This will position the text between position 27-37 left aligned:

{2, -10} = Third string [txt3], 2 = Text, -10 = amount of characters allowed for the string, - = left align


You want to pad the strings before writing them. This will give the correct number of spaces. See this tutorial: http://www.java2s.com/Code/CSharp/Language-Basics/Trimmingandpadding.htm


use "\t" instead of " "- it inserts tabs instead of spaces.

EDIT: my bad, didn't notice you were iterating over the table names. It's hacky, but you can use a varying number of \t's based on the largest table name and the current table name...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜