Link to home
Start Free TrialLog in
Avatar of pauledwardian
pauledwardian

asked on

C# Replace specific line number

How can I use this method to receive an integer index number and then replaces the string in that particular line:

public void replace (int index)
        {

             try
            {
                String strFile = File.ReadAllText("c:\\test.txt");

           
                if (strFile.Contains("A"))
                        {
                            strFile = strFile.Replace("P", "A");
                            strFile = strFile.Replace(" ", ";");

                            File.WriteAllLines("c:\\test.txt", strFile[index]);
                        
                        }
     
                        
                        

            }

            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

        }

Open in new window

Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Something like:
        public void replace(int index) // <-- zero based index: line #1 is at index 0 (zero)
        {
            try
            {
                String[] lines = File.ReadAllLines("c:\\test.txt");
                if (lines.Length > index)
                {
                    lines[index] = lines[index].Replace("P", "A").Replace(" ", ";");
                    File.WriteAllLines("c:\\test.txt", lines);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of pauledwardian
pauledwardian

ASKER

Fantastic!