locked
how to edit a line from a text file using c#

    Question

  • Hello all!

    My records are in a text file format.  I need to update a line from that text file using C#, how do I do that?  I'm new with C# so any suggestion will be greatly appreciated...

     

     

    Tuesday, May 02, 2006 12:02 AM

Answers

  • System.IO.File.ReadAllLines and System.IO.File.WriteAllLines is your best bet, then you can read the file in, find the line and change it, then write it again.  You cannot change a line in a file, you need to read it all, change it and write it all again.

     

    Tuesday, May 02, 2006 12:08 AM

All replies

  • System.IO.File.ReadAllLines and System.IO.File.WriteAllLines is your best bet, then you can read the file in, find the line and change it, then write it again.  You cannot change a line in a file, you need to read it all, change it and write it all again.

     

    Tuesday, May 02, 2006 12:08 AM
  • I read the file but I need to know how to change one line of the file (really just one character).  I checked to see if s.Equals("my string") but I can't seem to figure out how to change "my string" to my String".   Any help?

     

    Thanks.

    Mike

    Thursday, June 21, 2007 7:25 PM
  • I have the same question because i need to change a specific string inside a line in a file.ini

     

    Thanks!

     

    Monday, June 09, 2008 8:50 PM
  • StringBuilder newFile = new StringBuilder();

    string temp = "";

    string[] file = File.ReadAllLines(@"C:\Documents and Settings\john.grove\Desktop\1.txt");

    foreach (string line in file)

    {

        if (line.Contains("string"))

        {

            temp = line.Replace("string", "String");

            newFile.Append(temp + "\r\n");

            continue;

        }

        newFile.Append(line + "\r\n");

    }

    File.WriteAllText(@"C:\Documents and Settings\john.grove\Desktop\1.txt", newFile.ToString());

    • Proposed as answer by hasgarion Tuesday, May 15, 2012 7:49 AM
    Tuesday, June 10, 2008 12:04 AM
  • Insert, Update, Delete in text file using c# .net Window Application


    Application Name:
    AppSample


    Form1.Designer.cs
    ************************
            private System.Windows.Forms.Button button4;
            private System.Windows.Forms.Button button6;
            private System.Windows.Forms.TextBox txtLastName;
            private System.Windows.Forms.TextBox txtPhone;
            private System.Windows.Forms.TextBox txtMail;
            private System.Windows.Forms.TextBox txtWeb;
            private System.Windows.Forms.TextBox txtName;
            private System.Windows.Forms.Button button1;
            private System.Windows.Forms.Label label4;
            private System.Windows.Forms.Label label5;
            private System.Windows.Forms.Label label6;
            private System.Windows.Forms.Label label7;
            private System.Windows.Forms.Label label8;
            private System.Windows.Forms.ComboBox combo;

    Form1.cs
    ************
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;

    namespace AppSample
    {
        public partial class Form1 : Form
        {
            private DataText conDB;
            string txtvalue="";

            public Form1()
            {
                InitializeComponent();
                conDB = new DataText();
                conDB.Path = "C:/TextOperation.txt"; // dont use '\'!!
                fillCombo();
            }
            private void fillCombo()
            {
                this.combo.Items.Clear();
                int temp = conDB.Entries();
                if (temp > 0)
                {
                    temp--;
                    for (int i = 0; i <= temp; i++)
                    {
                        string name = "";
                        conDB.ReadEntrie(i, ref name);
                        if (name == "")
                        {
                            name = "<empty>";
                        }
                        this.combo.Items.Add(name);
                    }
                    combo.SelectedIndex = 0;
                }
            }
           
            private void button6_Click(object sender, EventArgs e)
            {

                conDB.InsertEntrie(txtName.Text, txtLastName.Text,
                   
                txtPhone.Text,txtMail.Text,txtWeb.Text);
                //txtID.Text = Convert.ToString(conDB.Entries()-1);
                txtvalue = Convert.ToString(conDB.Entries() - 1);
                fillCombo();
                txtName.Text = "";
                txtLastName.Text = "";
                txtPhone.Text = "";
                txtMail.Text = "";
                txtWeb.Text = "";
            }

            private void read(int id)
            {
                //txtID.Text = id.ToString();
                txtvalue = id.ToString();
                string str_name = "", str_lastname = "", str_phone = "", str_mail = "", str_web = "";

                bool result = conDB.ReadEntrie(id, ref str_name, ref str_lastname, ref str_phone, ref str_mail, ref str_web);
                txtName.Text = str_name;
                txtLastName.Text = str_lastname;
                txtPhone.Text = str_phone;
                txtMail.Text = str_mail;
                txtWeb.Text = str_web;
                if (!result) { MessageBox.Show("Invalid record"); }
            }
           

            private void button4_Click(object sender, EventArgs e)
            {
               string str_name = "", str_lastname = "", str_phone = "", str_mail = "", str_web = "";
               str_name =txtName.Text ;
               str_lastname =txtLastName.Text;
               str_phone =txtPhone.Text;
               str_mail =txtMail.Text;
               str_web =txtWeb.Text;
                //int id = Convert.ToInt32(txtID.Text);
               int id = Convert.ToInt32(txtvalue);           
               conDB.UpdateEntrie(id, str_name, str_lastname, str_phone, str_mail, str_web);
                fillCombo();
                txtName.Text = "";
                txtLastName.Text = "";
                txtPhone.Text = "";
                txtMail.Text = "";
                txtWeb.Text = "";
            }

            private void button1_Click(object sender, EventArgs e)
            {
                //int id = Convert.ToInt32(txtID.Text);
                int id = Convert.ToInt32(txtvalue);
                conDB.DeleteEntrie(id);
                read(0);
                fillCombo();
                txtName.Text = "";
                txtLastName.Text = "";
                txtPhone.Text = "";
                txtMail.Text = "";
                txtWeb.Text = "";
            }

        

            private void combo_SelectedIndexChanged(object sender, EventArgs e)
            {
                //txtID.Text = combo.SelectedIndex.ToString();
                txtvalue = combo.SelectedIndex.ToString();
                //read(Convert.ToInt32(txtID.Text));
                read(Convert.ToInt32(txtvalue));
            }

            private void Form1_Load(object sender, EventArgs e)
            {

            }

           

         
        }
    }
    DataText.cs
    ***************
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.IO;
    using System.Collections;
    /*Renan Rodrigues Duarte */
    /*Class for Plain Tex DataBase*/
    namespace AppSample
    {
        class DataText
        {

            private FileStream fs = null;
            private StreamReader sr = null;
            private StreamWriter sw = null;

            private string data_path = "";
            /// <summary>
            /// Get or Set the path of the text file!
            /// </summary>
            public string Path
            {
                get { return data_path; }
                set { data_path = value; }
            }
            public int Entries()
            {
                int count = 0;
                CreateConfigFile();
                try
                {
                    fs = new FileStream(data_path, FileMode.Open);
                    if (fs.Length >0)
                    {
                        sr = new StreamReader(fs);
                        while (sr.ReadLine() != null)
                        {
                            count++;
                        }
                        sr.Close();
                    }
                    fs.Close();
                }
                catch
                {
                    count = 0;
                }
                return count;
            }
        
            public bool ReadEntrie(int id, ref string name, ref string lastname, ref string phone, ref string mail, ref string website)
            {
                int count = 0;
                CreateConfigFile();
                try
                {
                    fs = new FileStream(data_path, FileMode.Open);
                    sr = new StreamReader(fs);
                    string temp = "";
                    bool cond = true;
                    while (cond==true)
                    {
                       
                        if ((temp=sr.ReadLine()) == null)
                        {
                            sr.Close();
                            fs.Close();
                            cond = false;
                            if (count==0)
                            return false;
                        }
                       

                        if (count == id)
                        {
                            string[] stringSplit = temp.Split('\t');
                            int _maxIndex = stringSplit.Length;
                            name = stringSplit[0];
                            lastname = stringSplit[1];
                            phone = stringSplit[2];
                            mail = stringSplit[3];
                            website = stringSplit[4];

                        }
                        count++;
                       
                    }
                   
                    sr.Close();
                    fs.Close();
                    return true;
                }
                catch
                {
                    return false;
                }

            }
            public bool ReadEntrie(int id, ref string name)
            {
                int count = 0;
                CreateConfigFile();
                try
                {
                    fs = new FileStream(data_path, FileMode.Open);
                    sr = new StreamReader(fs);
                    bool cond = true;
                    string temp = "";
                    while (cond == true)
                    {

                        if ((temp = sr.ReadLine()) == null)
                        {
                            sr.Close();
                            fs.Close();
                            cond = false;
                            if (count == 0)
                                return false;
                        }

                        if (count == id)
                        {
                            string[] stringSplit = temp.Split('\t');
                            int _maxIndex = stringSplit.Length;
                            name = stringSplit[0];
                        }
                        count++;

                    }

                    sr.Close();
                    fs.Close();
                    return true;
                }
                catch
                {
                    return false;
                }

            }
            public bool InsertEntrie(string name, string lastname, string phone, string mail, string website)
            {
                CreateConfigFile();
                try
                {
                    fs = new FileStream(data_path, FileMode.Append);
                    sw = new StreamWriter(fs);
                    //sw.WriteLine(name + ";" + lastname + ";" + phone + ";" + mail + ";" + website);
                    sw.WriteLine(name + '\t' + lastname + '\t'+ phone + '\t' + mail + '\t' + website);
                    sw.Close();
                    fs.Close();
                    return true;
                }
                catch(Exception ee)
                {
                    string temp = ee.Message;
                    return false;
                }
            }
            public bool UpdateEntrie(int id, string name, string lastname, string phone, string mail, string website)
            {
                int count = 0;
                CreateConfigFile();
                try
                {
                    fs = new FileStream(data_path, FileMode.Open);
                    sr = new StreamReader(fs);

                    string temp = "";
                    string temp2 = "";
                    while ((temp = sr.ReadLine()) != null)
                    {

                        if (count == id)
                        {
                            temp2 += name + '\t' + lastname + '\t' + phone + '\t' + mail + '\t' + website + "\r\n";
                        }
                        else
                        {
                            temp2 += (temp +"\r\n");
                        }
                        count++;

                    }
                    sr.Close();
                    fs.Close();

                    fs = new FileStream(data_path, FileMode.Create);
                    sw = new StreamWriter(fs);
                    sw.Write(temp2);
                    sw.Close();
                    fs.Close();
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            public bool DeleteEntrie(int id)
            {
                int count = 0;
                CreateConfigFile();
                try
                {
                    fs = new FileStream(data_path, FileMode.Open);
                    sr = new StreamReader(fs);

                    string temp = "";
                    string temp2 = "";
                    while ((temp = sr.ReadLine()) != null)
                    {

                        if (count != id)
                        {
                            temp2 += (temp + "\r\n");
                        }
                        count++;

                    }
                    sr.Close();
                    fs.Close();

                    fs = new FileStream(data_path, FileMode.Create);
                    sw = new StreamWriter(fs);
                    sw.Write(temp2);
                    sw.Close();
                    fs.Close();
                    return true;
                }
                catch
                {
                    return false;
                }
            }
            private bool CreateConfigFile()
            {
                try
                {
                    data_path = data_path.Replace((char)92, '/');
                    data_path = data_path.Replace((char)9, '/');
                    if (!File.Exists(data_path))
                    {

                        string temp = System.IO.Path.GetDirectoryName(data_path);
        
                        if (!Directory.Exists(temp))
                        {
                            Directory.CreateDirectory(temp);
                        }
                        fs = new FileStream(data_path, FileMode.CreateNew);
                        fs.Close();
                    }
                    return true;
                }
                catch //(Exception ee)
                {
                    return false;
                }
            }

        }
    }
    Thanks,
    S.S.Sivaprasad
    Tuesday, October 14, 2008 12:25 PM
  • this is exactly what i need.

    thanks
    Raj
    Thursday, November 26, 2009 5:48 AM
  • Excellent...
    Wednesday, December 09, 2009 6:06 PM
  • This consumes too much memory.
    Tuesday, April 27, 2010 3:39 PM
  • This consumes too much memory.

    My file has special charectors like -,_,.......So while writing back to a different file my data is being modified.

    Can someone suggest me a way in which I do not need to modify more that what I need to. Say only a word

    I need to modify and am writing the whole file all together. So can any body suggest me a way to do it.

    Tuesday, May 11, 2010 7:34 AM
  • Hello JonnGrove

    Thanks ,I am using your Code Its Realy Working Good. 

    Saturday, July 03, 2010 7:23 AM
  • i just start working in C#, m doing self study as my institute not offering this course,,,

    i have a problem while i making a calculator in C#,

    when i press the buton 2 ,, value of this button 2 prints but in this following format,

    System.Windows.Forms.TextBox, Text: 2

    so any1 can resolve my problem?

    Sunday, July 04, 2010 2:34 PM
  • hey .. heres a smiple way using File.ReadAllLines  and  File.WriteAllLines 
    make a form with 2 textbox and 2 buttons   
    txt1 will contain  a record to be added
    txt2 will contain a record to be removed if exists 
        TextWriter writer;
        TextReader reader;
        public Form1()
        {
          InitializeComponent();      
        }
    
        private void Add_btn_Click(object sender, EventArgs e)
        {
          reader = new StreamReader(File.OpenRead(@"C:\FriendLy\test.txt"));
          String line;
          while ((line = reader.ReadLine()) != null)
          { }
          reader.Close();
    
          writer = new StreamWriter(File.Open(@"C:\FriendLy\test.txt", FileMode.Append, FileAccess.Write));
          writer.WriteLine(txt1.Text);
          writer.Close();     
        }
    
        private void Remove_btn_Click(object sender, EventArgs e)
        {
          string [] _lines = File.ReadAllLines(@"C:\FriendLy\test.txt");
          string _search = txt2.Text;
          string [] new_lines = new string[_lines.Length-1];
          bool found = false;
          int i ;
          for(i = 0 ; i < _lines.Count() && !found ; i++ )
          {
            if (_lines[i].Equals(_search))
            {
              found = true ;
            }
            new_lines[i] = _lines[i];
          }
          if (!found)
          {
            return;
          }
          
          int j; 
          for (j = i+1; j < _lines.Count(); j++)
          {
            new_lines[j-1] = _lines[j];
          }            
          File.WriteAllLines(@"C:\FriendLy\test.txt",new_lines); 
    
        }
    
      }

    • Proposed as answer by nusja Wednesday, March 16, 2011 3:55 AM
    Saturday, January 29, 2011 9:00 AM
  • Easy way to replace some text in a textfile.

    using System;
    using System.IO;
    using System.Text.RegularExpressions;

    namespace ChangeTextInFiles
    {
        class Program
        {
            static void Main(string[] args) {

            /// Replaces text in a file.

            string filePath = @"c:\Windows\textfile.txt";
            string searchText = "exempleToReplace";
            string replaceText = "rePlaceByThis";
            ReplaceInFile(filePath, searchText, replaceText);
            }

            static public void ReplaceInFile(string filePath, string searchText, string replaceText)
            {

                StreamReader reader = new StreamReader(filePath);
                string content = reader.ReadToEnd();
                reader.Close();

                content = Regex.Replace(content, searchText, replaceText);

                StreamWriter writer = new StreamWriter(filePath);
                writer.Write(content);
                writer.Close();
            }
        }
    }

                                    
    • Edited by Essetee Monday, March 12, 2012 12:41 PM
    Monday, March 12, 2012 12:17 PM