27

I'm making a music player. It has 2 forms; one is the main area where you play music. The second form has a CheckedListBox where you select the mp3s you want. When I click a button, it saves the selection in a .txt file so I can access them in the first form, where I'll put the strings into the paths for music player to find the files.

This is the code in my second form, where I save the selected songs into .txt files.

private void selectbtn_Click(object sender, EventArgs e)
{
    if (File.Exists(@"C:\Users\Me\Desktop\JAM_MACHINE\JAMS\record.txt"))
    {
       File.WriteAllText(@"C:\Users\Me\Desktop\JAM_MACHINE\JAMS\record.txt", String.Empty);
    }

    string[] checkedtitles = new string[checkedListBox1.CheckedItems.Count]; 

    for (int ii = 0; ii < checkedListBox1.CheckedItems.Count; ii++)
    {
        checkedtitles[ii] = checkedListBox1.CheckedItems[ii].ToString();
    }
    string selectedSongs = String.Join(Environment.NewLine, checkedtitles); 

    songRecord.writeRecord(selectedSongs); //I initialised the class containing streamwriter/reader, and called it songRecord
    this.Close();   
}

The problem is, whenever I close the program and open it again, I can't rewrite/clear the .txt file. It just adds on to the existing file. Is there something I'm not doing right?

Here is my streamreader/writer codes. I'm pretty sure I closed it after running too, but perhaps somebody can figure out what's wrong:

namespace songss
{
    class DataRecord
    {
    public void writeRecord(string line)
    {
        StreamWriter sw = null;
        try
        {
            sw = new StreamWriter(@"C:\Users\Me\Desktop\JAM_MACHINE\record.txt", true);
            sw.WriteLine(line);
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Error: File not found.");
        }
        catch (IOException)
        {
            Console.WriteLine("Error: IO");
        }
        catch(Exception)
        {
            throw;
        }
        finally
        {
            if (sw != null)
                sw.Close();
        }
        }

 public void readRecord()
    {
        StreamReader sr = null;
        string myInputline;
        try
        {
            sr = new StreamReader(@"C:\Users\Me\Desktop\JAM_MACHINE\record.txt");
            while ((myInputline = sr.ReadLine()) != null) ; //readline reads whole line
            Console.WriteLine(myInputline);
        }
        catch (FileNotFoundException)
        {
            Console.WriteLine("Error: File not found");
        }
        catch(IOException)
        {
            Console.WriteLine("Error: IO");
        }
        catch (Exception)
        {
            throw;
        }
        finally
        {
            if (sr != null)
                sr.Close();
        }
    }
    }
    }
Nic
  • 12,220
  • 20
  • 77
  • 105
Manny
  • 325
  • 1
  • 3
  • 10
  • 3
    Why don't you just delete the file if it exists? – JohanP May 29 '17 at 06:15
  • 3
    What is your `songRecord.writeRecord` doing? If you're opening the file before wiping it, it may have already read in the current text. – Rob May 29 '17 at 06:16
  • According to the API documentation `File.WriteAllText` should replace the contents. If it doesn't, file a bug report. – Hubert Grzeskowiak May 29 '17 at 06:17
  • 2
    This is the code that is clearing the file. Please paste the code that writes the list into the file. That section contains the error. I am pretty sure you are probably not closing the stream writer or file. That is why the file is locked and second time when trying to write, the previous locked status is not cleared and causing problem. – brainless coder May 29 '17 at 06:24
  • Debug your code. And check by pausing if the file is actually being cleared. Then figure out what adds the content back in. – poke May 29 '17 at 06:32
  • Just a side question: Why don't you save your selection in a static property? You wouldn't need the file and the problem would solve it self. – Romano Zumbé May 29 '17 at 06:42
  • I've added my streamreader/writer codes. Pretty sure I closed them. Also I used a .txt file because that'll save the mp3 file names in different lines. That seems like an easier way to go about playing mp3 files consecutively. I'm not sure how to use a static property to solve that. – Manny May 29 '17 at 06:46

3 Answers3

56

WriteAllText

File.WriteAllText should do what you want.

Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.

StreamWriter

The StreamWriter class also has an option to overwrite/append:

Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to.

public StreamWriter(
    string path,
    bool append
)

Example:

using (StreamWriter writer = new StreamWriter("test.txt", false)){ 
    writer.Write(textToAdd);
}

Looking at your code, you're passing in true which means append.

sw = new StreamWriter(@"C:\Users\Me\Desktop\JAM_MACHINE\record.txt", true);
sw.WriteLine(line);

.NET Compact Framework

If you're stuck on a .NET version that doesn't support anything (e.g. compact framework), you can also implement WriteAllText yourself:

static void WriteAllText(string path, string txt) {
    var bytes = Encoding.UTF8.GetBytes(txt);
    using (var f = File.Open(path, FileMode.Create)) {
        f.Write(bytes, 0, bytes.Length);
    }
}
Nic
  • 12,220
  • 20
  • 77
  • 105
  • In C# .NET Compact Framework, there is no File.WriteAllText. What is the alternative? Thank you. – Rui Miguel Pinheiro Aug 06 '18 at 10:13
  • 1
    @RuiMiguelPinheiro I've added some code you might be able to use – Nic Aug 06 '18 at 23:39
  • 1
    OpenWrite is dangerous, if you write less bytes that are already in the file, the file will contain mix of new and old data. I suggest File.Open with FileMode.Create instead. – Hogan Dec 21 '18 at 18:00
  • 1
    @Hogan thanks for the feedback, I've updated the example – Nic Dec 22 '18 at 08:50
4

Use this

File.WriteAllText(@"C:\Users\Me\Desktop\JAM_MACHINE\JAMS\record.txt", line);

instead of

sw = new StreamWriter(@"C:\Users\Me\Desktop\JAM_MACHINE\record.txt", true);
sw.WriteLine(line);
Nic
  • 12,220
  • 20
  • 77
  • 105
-3

Refer this link for Solution Provided by Microsoft: (https://msdn.microsoft.com/en-us/library/system.io.file.appendtext(v=vs.110).aspx)

Here is code to append existing File:

StreamWriter writer = File.AppendText(Filepath);
writer.WriteLine(content);
writer.Close();
dferenc
  • 7,918
  • 12
  • 41
  • 49
AutomationNerd
  • 406
  • 1
  • 5
  • 12