streamWriter rewrite the file or append to the fil

2020-01-28 16:47发布

问题:

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#

回答1:

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


回答2:

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);    
    }
}


回答3:

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");


回答4:

You can start by using the FileStream and then passing that to your StreamWriter.

FileStream fsOverwrite = new FileStream("C:\\test.txt", FileMode.Create);
StreamWriter swOverwrite = new StreamWriter(fsOverwrite);

or

FileStream fsAppend = new FileStream("C:\\test.txt", FileMode.Append);    
StreamWriter swAppend = new StreamWriter(fsAppend);


回答5:

So what is the result of your code?

I would expect the file to contain nothing but the number 4, since the default behavior is to create/overwrite, but you are saying that it is not overwriting?

You should be able to make it overwrite the file by doing what you are doing, and you can append by making a FileStream with FileMode.Append.