Question

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)
        {

        }
    }

}

Was it helpful?

Solution

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(); 
}

OTHER TIPS

To answer your question:

Where should I put the text file...?

You haven't specified a path to cookies.txt so the program will look for it in the same directory where it's running. If you change cookies.txt to include a path, for example C:\dev\cookies.txt, then you can store the file wherever you like.

That will allow you to get past the file not found error and address any other problems you have in there.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top