如何格式化我的Stream Writer以写入我的文本文件?

时间:2012-04-13 22:46:02

标签: c# asp.net forms stream

文本文件用于描述Web浏览器上的游戏状态。所以我需要将nameWriter.WriteLine格式化为类似的内容。

Output to text file:
playerOneName, playerTwoName, _ , _ , _ , _ , _ , _ , _ , _

我知道这可能听起来像“哦,只是写这条线!”但不是,下划线是一个空的字段,将由我的StreamWriter取代,它跟踪玩家在一个tic tac toe网页游戏中的移动。我可以使用什么代替下划线来使我的读写空间可用?

这是我的StreamWriter,现在我只添加了播放器名称。

您能告诉我如何将输出格式化为文本吗?

也许在数组中将它分开?并使用数组DelimiterList键出逗号?

    string[] lineParts... and reference the linePart[0-11] 
and then do a lineParts = line.Split(delimiterList)?

这是我的写代码。

private void WriteGame(string playerOneName, string playerTwoName, string[] cells)
    {
        StreamWriter gameStateWriter = null;
        StringBuilder sb = new StringBuilder();
        try
        {
            gameStateWriter = new StreamWriter(filepath, true);
            gameStateWriter.WriteLine(playerOneName + " , " + playerTwoName);
            string[] gameState = { playerOneName, 
            playerTwoName, null, null, null, null, 
    null, null, null, null, null };//I cannot use null, they will give me errors
            foreach (string GameState in gameState)
            {
                sb.Append(GameState);
                sb.Append(",");
            }
            gameStateWriter.WriteLine(sb.ToString());
        }
        catch (Exception ex)
        {
            txtOutcome.Text = "The following problem ocurred when writing to the file:\n"
               + ex.Message;
        }
        finally
        {
            if (gameStateWriter != null)
                gameStateWriter.Close();
        }
    }

最后如果playerOneName已经在文本文件中,我该如何在它之后专门编写playerTwoName并检查它是否存在?

使用Visual Studio '08 ASP.NET网站和表单

2 个答案:

答案 0 :(得分:3)

首先,定义一个事实,即下划线是一个特殊的东西,对你来说意味着空,而逗号是你的分隔符:

const string EMPTY = "_";
const string DELIMITER = ",";

其次,不要在逗号和值之间写空格,这样只会让你以后的生活变得更加困难:

// removed spaces
gameStateWriter.WriteLine(playerOneName + DELIMITER + playerTwoName);

现在您的GameState已准备就绪:

string[] gameState = { playerOneName, playerTwoName, EMPTY, EMPTY, EMPTY, EMPTY, 
                       EMPTY, EMPTY, EMPTY, EMPTY, EMPTY,  };

要检查播放器2是否已存在,您需要打开并读取现有文件,并检查第二个令牌是否为空。也就是说,如果您已阅读该文件;

var line = "..."; // read the file until the line that .StartsWith(playerOne)
var playerTwo = line.Split(DELIMITER)[1];

if (playerTwo == EMPTY)
{
     // need to store the real playerTwo, otherwise leave as is
}

答案 1 :(得分:0)

您可以保留代码,但不要在当前代码中sb.Append(GameState);执行sb.Append(GameState??"_");

“??”在C#中为null-coalescing operator - 因此null ?? "_"的结果为“_”而"SomeValue"??"_"为“SomeValue”。