Click here to Skip to main content
15,885,546 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Good day,
I have a question about rewriting the text in the line I'm looking for. The code works if I write the line number, but as soon as I try to find the line number, I don't know how.

I will be happy for any advice and help.

Thank you very much.

What I have tried:

C#
public MainWindow()
       {
           InitializeComponent();
       }

       private void Grid_Loaded(object sender, RoutedEventArgs e)
       {
           TextBox.Focus();
       }

       private void HledatButton_Click(object sender, RoutedEventArgs e)
       {
           string file = TextBox.Text;
           List<string> files = Directory.GetFiles(file, "*.csproj", SearchOption.AllDirectories).ToList();
          foreach (string pathFile in files)
           {
               string[] lines = File.ReadAllLines(pathFile);

               var newText = "";
               var oldText = "";
               int lineEdit =0;
               foreach (string object in lines)
               {
                   if (objekt.Contains(oldText))
                   {
                       lineEdit++;

                   }
                   lines[lineEdit - 1] = newText;
                   File.WriteAllLines(pathFile, lines);
               }

           }


       }


Application is in c# and WPF
Posted
Updated 5-Nov-21 1:14am
Comments
BillWoodruff 5-Nov-21 7:15am    
put breakpoints in your code; single-step through it using F11, examine the values of variables ,,, that will show you what the problem is.
PIEBALDconsult 5-Nov-21 11:32am    
"Editing" text files is fraught with peril. Basically, don't try.
I recommend using an XmlDocument to read/load the file. Use XPath to find what you want to change. Make the change. Then write the file.
Further, I would write the new file as a .tmp, rename the existing file as .bak, and then rename the .tmp -- so you still have a backup in case something went wrong.

1 solution

Use a for loop instead of a foreach loop, and only write the updated content back to the file outside of the loop.
C#
for (int index = 0; index < lines.Length; index++)
{
    string line = lines[index];
    if (line.Contains(oldText))
    {
        lines[index] = newText;
    }
}

File.WriteAllLines(pathFile, lines);

NB: Since csproj files are XML, it may be safer to load and manipulate them using an XML parser - eg: LINQ to XML[^].
 
Share this answer
 
Comments
dejf111 5-Nov-21 7:23am    
Thank you very much excellent answer!!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900