I am trying to write to a specific line part using Stream Writer, here’s what I have so far:
The exception message is giving me: Index was outside the bounds of the array.
private void WriteData(string playerName)
{
StreamWriter nameWriter = null;
StringBuilder sb = new StringBuilder();
try
{
string line = "";
string namePartOne = line.Split(DELIMITER)[0];
string namePartTwo = line.Split(DELIMITER)[1];
if (namePartOne != EMPTY)
{
namePartTwo = playerName;
string[] gameState = { namePartOne, namePartTwo, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY };
sb.Append(gameState);
nameWriter.WriteLine(String.Join(",", gameState));
}
else
{
nameWriter = new StreamWriter(filepath, true);
string[] gameState = { playerName, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY };
nameWriter.WriteLine(String.Join(",", gameState));
}
}
catch (Exception ex)
{
txtTextBox2.Text = "The following problem ocurred when writing to the file:\n"
+ ex.Message;
}
finally
{
// Closing the StreamWriter should close it
// AND its underlying FileStream
if (nameWriter != null)
nameWriter.Close();
}
}
I am trying to out put this to my text file:
playerOneName, playerTwoName, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY, EMPTY
Basically this writer is used to write player one’s from his browser, and player two’s name from another browser/tab. I first want to check if player one’s name is written in the first field, if it is, I will write then second player in the second field. The other field are left empty to describe the game state when the game is run.
I might have logic problems, please point out if you see any. Can I use regular expression to compare and validate my players are there?
I need to Stream Read this file before I can Stream Write the file, is that correct?
I am running Visual Studio ’08 using APS.NET website and forms.
this will result in the index out of bounds error, as you are splitting an empty string (which will return one item) and then trying to access the second item of that one-item list.
Also, might I suggest rather than using a StringBuilder, just do
to create your output string.
Here’s a possible overall solution (apologies for any errors, as I don’t have a compiler to hand):
Note: ‘using’ is a handy way to get that try/finally which closes the stream for free (you’ll still have to catch exceptions though).