Подтвердить что ты не робот

StreamWriter переписать файл или добавить в файл

Я использую этот

for($number=0; $number < 5; $number++){
StreamWriter x = new StreamWriter("C:\\test.txt");
                x.WriteLine(number);
                x.Close();

}

если что-то находится в test.text, этот код не будет перезаписывать его. У меня есть 2 вопроса

1: how can I make it overwrite the file
2: how can I append to the same file

с использованием С#

4b9b3361

Ответ 1

Попробуйте перечислитель FileMode:

        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 по умолчанию - это создать новый файл или перезаписать его, если он существует. Чтобы добавить к файлу, вам нужно использовать перегрузку, которая принимает логическое значение и устанавливает значение true. В вашем примере кода вы будете переписывать test.txt 5 раз.

using(var sw = new StreamWriter(@"c:\test.txt", true))
{
    for(int x = 0; x < 5; x++)
    {
        sw.WriteLine(x);    
    }
}

Ответ 3

Вы можете передать второй параметр в StreamWriter в enable или disable, добавляя к файлу:

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

в 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

Вы можете начать с использования FileStream, а затем передать его в StreamWriter.

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

или

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

Ответ 5

Итак, каков результат вашего кода?

Я бы ожидал, что файл не содержит ничего, кроме номера 4, поскольку поведение по умолчанию заключается в создании/перезаписи, но вы говорите, что оно не переписывается?

Вы должны уметь перезаписывать файл, выполняя то, что вы делаете, и можете добавить его, создав FileStream с FileMode.Append.