I am using this
for($number=0; $number < 5; $number++){
StreamWriter x = new StreamWriter("C:\\test.txt");
x.WriteLine(number);
x.Close();
}
if something is in test.text, this code will not overwrite it. I have 2 questions
1: how can I make it overwrite the file
2: how can I append to the same file
using C#
StreamWriter and StreamReader write characters to and read characters from streams. The following code example opens the log. txt file for input, or creates it if it doesn't exist, and appends log information to the end of the file.
StreamWriter(String, Boolean) 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. If the file does not exist, this constructor creates a new file.
StreamWriter. WriteLine() method writes a string to the next line to the steam. The following code snippet creates and writes different author names to the stream.
NET core 3.0 and later versions, you can call Move String, String, Boolean setting the parameter to overwrite to true, which will replace the file if it exists. In all . NET versions, you can call delete(string) before calling Move, which will only delete the file if it exists.
Try the FileMode enumerator:
FileStream fappend = File.Open("C:\\test.txt", FileMode.Append); // will append to end of file
FileStream fcreate = File.Open("C:\\test.txt", FileMode.Create); // will create the file or overwrite it if it already exists
StreamWriters default behavior is to create a new file, or overwrite it if it exists. To append to the file you'll need to use the overload that accepts a boolean and set that to true. In your example code, you will rewrite test.txt 5 times.
using(var sw = new StreamWriter(@"c:\test.txt", true))
{
for(int x = 0; x < 5; x++)
{
sw.WriteLine(x);
}
}
You can pass a second parameter to StreamWriter
to enable
or disable
appending to file:
in C#.Net
:
using System.IO;
// This will enable appending to file.
StreamWriter stream = new StreamWriter("YourFilePath", true);
// This is default mode, not append to file and create a new file.
StreamWriter stream = new StreamWriter("YourFilePath", false);
// or
StreamWriter stream = new StreamWriter("YourFilePath");
in C++.Net(C++/CLI)
:
using namespace System::IO;
// This will enable appending to file.
StreamWriter^ stream = gcnew StreamWriter("YourFilePath", true);
// This is default mode, not append to file and create a new file.
StreamWriter^ stream = gcnew StreamWriter("YourFilePath", false);
// or
StreamWriter^ stream = gcnew StreamWriter("YourFilePath");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With