0

and in my c# program, what i am trying to do is whenever in a game you say !mypickaxe, it tells you what pickaxe you have. Recently I figured out a way to save it to a .txt file so the data could be used more than one time, but of course im getting "object reference not set to an instance of an object". Here is the part that has the error:

StreamReader streemy = new StreamReader("pickaxes.txt");
string line = streemy.ReadLine();
string[] thing = line.Split('=');
player[userID].pickaxe = Convert.ToInt32(thing[1]);

In the .txt file, it saves like this: username=pickaxe And so it's supposed to get the number, but i get that error on this line:

string[] thing = line.Split('=');

Does anybody know how to fix this and/or why this happens? Thanks in advance!

1
  • streemy.ReadLine() returns null when end of file. line.Split throws NullReferenceException Commented Nov 16, 2013 at 15:06

2 Answers 2

3

try and check if streemy.ReadLine returns null:

string line = streemy.ReadLine();

if(!string.IsNullOrEmpty(line))
{
  string[] thing = line.Split('=');
  player[userID].pickaxe = Convert.ToInt32(thing[1]);
}

you could even go futher and check thing and player[userID]

if(!string.IsNullOrEmpty(line))
{
  string[] thing = line.Split('=');
  if(thing.Count() > 1 && player[userID] != null)
    player[userID].pickaxe = Convert.ToInt32(thing[1]);
}

also I would wrap the stream in a using block:

using(StreamReader streemy = new StreamReader("pickaxes.txt"))
{
   //code omitted
}
Sign up to request clarification or add additional context in comments.

Comments

0

i would suggest to use File.ReadAllLines() to avoid all Errors.

string [] line=System.IO.File.ReadAllLines("pickaxes.txt");    
string[] thing = line[0].Split('=');//here 0 can be any required index
player[userID].pickaxe = Convert.ToInt32(thing[1]);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.