Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Overwrite A File If It Already Exists?

Tags:

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();         }     }     }     } 
like image 841
Manny Avatar asked May 29 '17 06:05

Manny


People also ask

How do I overwrite an existing file?

Overwriting a File, Part 1 To edit the settings for a file, locate the file you wish to overwrite and hover over the file name. Click the chevron button that appears to the right of the file name and select Overwrite File from the menu.

What happens if a file already exists?

The error message "File Already Exists" or "File Already in Use" indicates that a file CTI Navigator Desktop is attempting to use is already open, locked or corrupted. The fix is to replace a corrupted file, and close, unlock or replace a locked file.

How do you overwrite a file in Python if it exists?

To overwrite a file, to write new content into a file, we have to open our file in “w” mode, which is the write mode. It will delete the existing content from a file first; then, we can write new content and save it.


Video Answer


2 Answers

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);     } } 
like image 197
Nic Avatar answered Oct 06 '22 16:10

Nic


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); 
like image 24
Brian Daniel Tiongco Avatar answered Oct 06 '22 16:10

Brian Daniel Tiongco