EthanBar EthanBar - 28 days ago 6
C# Question

C# Streamreader problems

I'm building a program that has you input a number and remembers it when you re-open the program. It uses a text file to save the number in. I'm using streamreader to read the text file to get the number you entered last, but it always throws an exception. Where should I put the text file or change my code so it can read and edit the text? Here is my code:

namespace Cookie_Clicker
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{

public MainWindow()
{
InitializeComponent();
}

private void tb_TextBox(object sender, RoutedEventArgs e)
{

}

private void add_Click(object sender, RoutedEventArgs e)
{
try
{
using (StreamReader sr = new StreamReader("cookies.txt"))
{
int data = Convert.ToInt16(sr.ReadToEnd());
tb.Text = Convert.ToString(data + 1);
}
}
catch (Exception)
{
MessageBox.Show("Your cookie text file is missing!");
}
}

private void reset_Click(object sender, RoutedEventArgs e)
{

}
}


}

Answer Source

Every time it says "Your cookie text file is missing!"

Problem 1: You are not specifying proper path of your input file.

Solution 1: You need to get the Currentpath of your application from where it is running and then combine it with the filename using Path.Combine() method.

Try This:

var path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"cookies.txt");
using (StreamReader sr = new StreamReader(path))
{
    int data = Convert.ToInt16(sr.ReadToEnd());
    tb.Text = Convert.ToString(data + 1);
}

Suggestion : You need to always display the Error message in Catch block to identify the problem.

You can call ToString() on Exception object to get the complete exception info.

catch (Exception ex) 
{
    MessageBox.Show(ex.ToSTring(); 
}