0

您好,我有一个名为 gameWriter 的 StreamWriter。我可以使用字符串生成器来格式化我的 Stream Writer 吗?我希望结果如下所示: playerOneName 和 playerTwoName 是需要写入的变量。有人可以给我一个示例代码来显示以下内容:

Output:
playerOnename, playerTwoname, _, _, _, _, _, _, _, _, _,


private void WriteData(string playerOneName, string playerTwoName)
    {
        StreamWriter gameStateWriter = null;

        try
        {
            gameStateWriter = new StreamWriter(filepath, true);
            gameStateWriter.WriteLine(playerOneName + " , " + playerTwoName);
        }
        catch (Exception ex)
        {
            txtOutcome.Text = "The following problem ocurred when writing to the file:\n"
               + ex.Message;
        }
        finally
        {
            if (gameStateWriter != null)
                gameStateWriter.Close();
        }
    }

是的,这些是下划线,它们应该表示准备好写入空间以保存一些文本。

我正在使用运行 ASP.NET 网站和表单的 Visual Studio '08。

4

1 回答 1

2

尽管我建议使用循环附加到构建器,但如何将流编写器与字符串构建器一起使用。

StringBuilder builder = new StringBuilder();

builder.Append(playerOneName)
builder.Append(",")
builder.Append(playerTwoName)
builder.Append(",")
StreamWriter  nameWriter = new StreamWriter(filepath, true);
nameWriter.WriteLine(builder.ToString());

您只需将所有变量存储在数组中

string[] names = {playerOneName, playerTwoName, playerThreName};
foreach(string item in names)
{

    builder.Append(item)
    builder.Append(",")
}
于 2012-04-13T00:41:57.560 回答