开发者

streamWriter rewrite the file or append to the file

开发者 https://www.devze.com 2023-04-04 19:45 出处:网络
I am using this for($number=0; $number < 5; $number++){ StreamWriter x = new StreamWriter(\"C:\\\\test.txt\");

I am using this

for($number=0; $number < 5; $number++){
StreamWriter x = new StreamWriter("C:\\test.txt");
                x.WriteLine(number)开发者_JS百科;
                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#


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


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号