Reputation: 1489
The text file is being used to describe the state of the game on a web browser. So I need to format my nameWriter.WriteLine to look something like.
Output to text file:
playerOneName, playerTwoName, _ , _ , _ , _ , _ , _ , _ , _
I know this may sound like "Oh just writeLine this!" But no, the underscores are an empty field that are to be replace by my StreamWriter, it tracks the moves of the player in a tic tac toe web game. What can I use instead of the underscore to make that space available for my read and write?
Here is my StreamWriter, right now I only have it adding the player name.
Maybe separate it in an array? and use a array DelimiterList to key out the commas?
string[] lineParts... and reference the linePart[0-11]
and then do a lineParts = line.Split(delimiterList)?
Here is my write code.
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();
}
}
Lastly if playerOneName is already in the text file, how do I specifically write playerTwoName after it and check that it is there?
Using Visual Studio '08 ASP.NET website and forms
Upvotes: 0
Views: 3564
Reputation: 100527
You can keep your code, but instead of sb.Append(GameState);
do sb.Append(GameState??"_");
in your current code.
"??" is null-coalescing operator in C# - so result of null ?? "_"
is "_" and "SomeValue"??"_"
is "SomeValue".
Upvotes: 0
Reputation: 15618
Firstly, define the fact that underscore is a special thing that means empty for you, and that commas are your delimiter:
const string EMPTY = "_";
const string DELIMITER = ",";
Secondly, don't write spaces between the comma and the values, that will just make your life more difficult later on:
// removed spaces
gameStateWriter.WriteLine(playerOneName + DELIMITER + playerTwoName);
Now your GameState is ready to be created:
string[] gameState = { playerOneName, playerTwoName, EMPTY, EMPTY, EMPTY, EMPTY,
EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, };
To check if player two is already there, you need to open and read the existing file, and check to see if the second token is not empty. That is, if you've read the file;
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
}
Upvotes: 3