Click here to Skip to main content
15,882,464 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am very new to C# and programming in general.

Currently, my project has a button with an onclick method that saves the contents of a listbox to a file in the same location as the .exe file. This works fine.

But the problem comes when I try using StreamReader to populate the listbox from the file.
As far as I can tell, the file keeps getting duplicated and moved into the resources folder so that I am writing and reading to two different files.

I am hesitant to hardcode a path such as C:/user/ etc as I need this project to run on someone elses pc.

Thank you for your help.

What I have tried:

My current StreamWriter code:

C#
private void btnSave_Click(object sender, RoutedEventArgs e)
      {
          try
          {
              StreamWriter fileWriter = new StreamWriter("items.txt", true);
              //If no item is selected
              if (lbxSales.SelectedIndex == -1)
              {
                  foreach (string i in lbxSales.Items)
                  {
                      //Writes every item from lbxSales to items.txt
                      fileWriter.WriteLine(i);

                  }
                  fileWriter.Close();
              }
              else
              {
                  //If an item is selected, write that item to Items.txt
                  fileWriter.WriteLine(lbxSales.SelectedItem);
                  fileWriter.Close();
              }
          }
          catch (Exception ex)
          {
              MessageBox.Show("Unexpected error: " + ex);
          }
      }


My current StreamReader code:

C#
private void btnLoad_Click(object sender, RoutedEventArgs e)
        {            
            StreamReader fileReader = new StreamReader("items.txt");
            while(!fileReader.EndOfStream)
             {
                lbxSales.Items.Add(fileReader.ReadLine());                
             }
            fileReader.Close();
            
        }
Posted
Updated 4-Oct-21 16:46pm
v3
Comments
PIEBALDconsult 4-Oct-21 19:53pm    
I would use a FileInfo and not keep repeating the name of the file.
Dave Kreskowiak 4-Oct-21 21:31pm    
You're going to be surprised when you find out you cannot write to files under any folder under Program Files.
Member 15382039 4-Oct-21 22:07pm    
Not sure what this means, I haven't had any issues writing to a file, more so reading from it.
Dave Kreskowiak 4-Oct-21 22:12pm    
Because it's on your machine and you're an admin on it.

On normal user machines, everything under Program Files is ReadOnly. If you install your app under Program Files, like everyone else does, you will not be able to create/write files "in the same folder as the .exe".
Member 15382039 4-Oct-21 22:18pm    
It's not important to me that the file is under program files. Previously, I was able to get the file to save under documents, without hardcoding a path using this code:
String fileName = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
fileName = fileName + "\\items.txt";
if (! File.Exists("items.txt"))
{
File.Create("items.txt");
}

However, I was met with the same issue of not being able to get my program to read from it.

1 solution

The solution to this is to write debuggable code and use the debugger.

Put a breakpoint on the first line of this function and run your app. What did you do to get this code to run? Do that again, and when the debugger stops the execution of the app, it'll show you in yellow which line is about to execute next. While the code is stopped, you can hover the mouse over variables and object properties to see their contents.

Doing crap like this is NOT debuggable code:
C#
lbxSales.Items.Add(fileReader.ReadLine());
Separate those operations into their own lines so you can see what, if anything, was read.
C#
string content = fileReader.ReadLine();
lbxSales.Items.Add(content);
Next, did anything get written to the file at all? Was it what you expected given your input? From what I can see, probably not.

This works:
C#
private void SaveButton_Click(object sender, EventArgs e)
{
    using (StreamWriter sw = new StreamWriter("Items.txt", true))
    {
        // If no item is selected
        if (listBox1.SelectedIndex == -1)
        {
            foreach (var item in listBox1.Items)
            {
                sw.WriteLine(item);
            }
        }
    }
}

private void LoadButton_Click(object sender, EventArgs e)
{
    using (StreamReader sr = new StreamReader("Items.txt"))
    {
        while (!sr.EndOfStream)
        {
            string content = sr.ReadLine();
            listBox1.Items.Add(content);
        }
    }
}
Oh, and get into the habit of using "using" blocks on Disposable objects.
 
Share this answer
 
Comments
Member 15382039 5-Oct-21 0:16am    
Thank you for your response, you have solved my issue.
It is embarrassing to admit, when using the breakpoints, I realized that the btnLoad method was not being triggered at all, somehow I had messed up my xaml code for the click event!! Must have accidentally deleted it...

I will work on making my code more debuggable in the future, as well as figuring out "using" blocks.

My only concern now is whether this will run on someone elses pc, you mentioned it won't work if it's installed in program files, but if the program is not installed in program files then saving to the same location as the .exe is perfectly fine, no?

Thank you for your help, I had been stumped for days.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900