Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

StreamWriter replace line with a new text

Is it possible to replace the text in a text file with a new text without erasing the other data, here is my sample code, but its not working, I know there's a problem with it but I can't figure out, thanks,

private void button1_Click_1(object sender, EventArgs e)
{
    StreamReader sr = new StreamReader("test10101.txt");
    List<string> lines = new List<string>();
    while (!sr.EndOfStream)
        lines.Add(sr.ReadLine());
    output = Convert.ToInt32(textBox1.Text);
    newbal = Convert.ToInt32(lines[0]) - output;
    MessageBox.Show("Please get your cash....\n\nYour new balance is: $" + newbal);
    sr.Close();
    {
        string linetoreplace = lines[0];
        int newlinevalue = newbal;
        string contents = sr.ReadToEnd();

        StreamWriter sw = new StreamWriter("test10101.txt" + ".tmp");
        //contents = Regex.Replace(contents, linetoreplace, newlinevalue.ToString());
        contents = contents.Replace(linetoreplace, newlinevalue.ToString());
        sw.WriteLine(contents);
        sw.Close();

    }

I'm wondering if I use the Regex or directly replace the line,

like image 311
Pyromancer Avatar asked Jan 26 '13 03:01

Pyromancer


People also ask

Does StreamWriter overwrite?

StreamWriter(String, Boolean, Encoding)If the file exists, it can be either overwritten or appended to.

How do you overwrite a line in a file in C#?

ReadWrite, FileShare. None); with this stream, you can read until you get to the point where you want to make changes, then write. Keep in mind that you are writing bytes, not lines, so to overwrite a line you will need to write the same number of characters as the line you want to change.

What is StreamWriter and StreamReader in C#?

The StreamReader and StreamWriter classes are used for reading from and writing data to text files. These classes inherit from the abstract base class Stream, which supports reading and writing bytes into a file stream.


1 Answers

You could do it a lot more easily:

        string[] lines = System.IO.File.ReadAllLines("test");
        lines[0] = /* replace with whatever you need */
        System.IO.File.WriteAllLines("test", lines);

hope this helps

also I'd suggest using int.TryParse if you don't want an exception to be raised in your portion of code in case the first line of the file or the textbox values aren't numeric

if you really want to use the streamwriter you could go with this, also a simpler way:

line[0] = newbal.ToString();
foreach(string s in lines)
    sw.WriteLine(s);
like image 66
ppetrov Avatar answered Oct 16 '22 23:10

ppetrov