How To Overwrite A File If It Already Exists?
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);
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);
}
}