简体   繁体   中英

Saving to end of exsisting text file c#

I have the following code written as I want to save a string to the end of a text file in the form of a list.

However, at the moment when I try to save something, it deletes all previous text in the file and just adds the most recent one. The following is my code:

using (var writer = new StreamWriter(@"C:\Users\Falconex\Documents\Visual Studio 2015\Projects\Test2\Test2\bin\Debug\Product.txt"))
{
    writer.WriteLine(productTextBox.Text + Environment.NewLine);
    writer.Close();
}

Thank you in advance, Lucy

You're currently just overwriting the contents of the file, every time you write.

StreamWriter has a second parameter you have to set to true to append text: https://msdn.microsoft.com/library/36b035cb(v=vs.110).aspx

using (var writer = new StreamWriter(@"C:\Path\To\file.txt", true))
{
    writer.WriteLine(productTextBox.Text + Environment.NewLine);
    writer.Close();
}

You can do it more easier. Use some of static methods on class "File" (AppendAllLines, AppendText, AppendAllText). For example:

 File.AppendAllLines("filename.txt", new string[] { "my appended text" });

Hi try to add this code to new StreamWriter constructor

new FileStream(@"path/to/file", FileMode.Append, FileAccess.Write)

for more info look at https://msdn.microsoft.com/cs-cz/library/wtbhzte9(v=vs.110).aspx

That's because you are overwriting the previous content. You need to read the content first store it temporarily and write again with the new text. Something like this:

//Reading text
string text = System.IO.File.ReadAllText(@"C:\Users\Falconex\Documents\Visual Studio 2015\Projects\Test2\Test2\bin\Debug\Product.txt");
using (var writer = new StreamWriter(@"C:\Users\Falconex\Documents\Visual Studio 2015\Projects\Test2\Test2\bin\Debug\Product.txt"))
{
    writer.WriteLine(text + productTextBox.Text + Environment.NewLine);
    writer.Close();
}
using (var writer = new StreamWriter(@"C:\Users\Falconex\Documents\Visual         Studio 2015\Projects\Test2\Test2\bin\Debug\Product.txt",true))
            {
                writer.WriteLine(productTextBox.Text + Environment.NewLine);
                writer.Close();
            }

try this:

 using (var writer = new StreamWriter(filepath, true))
    {
        {
        writer.Write(productTextBox.Text + Environment.NewLine);
        }
    writer.Close();
    }

that true parameter tells the StreamWriter to Append the text if the file exists

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM