将WriteLine写入文件 - 文本部分的位置相同

时间:2013-03-05 16:10:53

标签: c# formatting

我正在生成名单和值列表。 未格式化它看起来像这样:

 - Atrox (Jesse Stone) - Level: 4
 - InternetInk (Benjamin Chiryoku) - Level: 4
 - Eliot_Ness (James Carter) - Level: 4
 - Kones (Dmitri Schukov) - Level: 4
 - 611er (Falk vanAlk) - Level: 3
 - Julian (Linus Torvalds) - Level: 2
 - Bot (Staat) - Level: 1
 - Hawke (Garen Hawke) - Level: 1

但我希望它看起来像这样:

- Atrox (Jesse Stone)                   - Level: 4
- InternetInk (Benjamin Chiryoku)       - Level: 4
- Eliot_Ness (James Carter)             - Level: 4
- Kones (Dmitri Schukov)                - Level: 4
- 611er (Falk vanAlk)                   - Level: 3
- Julian (Linus Torvalds)               - Level: 2
- Bot (Staat)                           - Level: 1
- Hawke (Garen Hawke)                   - Level: 1

我的写作线是:

fileWriter.WriteLine(" - " + player.accountName + " (" + player.charName + ") - Level: " + player.level);

1 个答案:

答案 0 :(得分:3)

使用String.PadRight()方法:

public string FormatPlayerInfo(string accountName, string charName, string level)
{
    int padRight = 45;
    string account = String.Format("- {0} ({1})", accountName,
                                                charName)
                            .PadRight(padRight);
    return String.Format("{0} - Level: {1}", account, level);
}

用法:

file.WriteLine(FormatPlayerInfo(
                 player.accountName, 
                 player.charName, 
                 player.level));