How to overwrite a file if it already exists?

I am making a music player. It has 2 forms; one of them is the main area where you play music. The second form has a CheckedListBox, where you select the mp3 you need. When I click the button, it saves the selection in the .txt file, so I can access them in the first form, where I will put the lines in the path for the music player to find the files.

This is the code in my second form, where I save the selected songs to .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 that whenever I close the program and open it again, I cannot overwrite / clear the .txt file. It just adds an existing file. Is there something that I am not doing right?

Here are my read / write codes. I am sure that I also closed it after launch, but maybe someone can understand what happened:

 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(); } } } } 
+8
source share
4 answers

WriteAllText

File.WriteAllText should do what you want.

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

Streamwriter

The StreamWriter class also has the ability to overwrite / add:

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

 public StreamWriter( string path, bool append ) 

Example:

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

Looking at your code, you pass in true which means adding.

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

.NET Compact Framework

If you are stuck in a .NET version that does not support anything (e.g. compact structure), 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); } } 
+17
source
Nicholas is right. I changed my StreamWriter as false and solved the problem. I did not need to use File.WriteAllText since passing it as false will not be added.

Thanks!

+1
source

Use this

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

instead

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

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

Here is the code to add an existing file:

 StreamWriter writer = File.AppendText(Filepath); writer.WriteLine(content); writer.Close(); 
0
source

Source: https://habr.com/ru/post/1268312/


All Articles