-2

I want remove a text if the program finds the text to replace, so I prepared this code:

  string[] lines = File.ReadAllLines(@"pathtofile");
        int Object = 0;
        foreach (string line in lines)
        {

            if (line.Contains("Object"))
            {
                MessageBox.Show("contain!");
                dsObject++;
            }

            if (Object == 1)
            {
                line.Replace("Object", " ");
                MessageBox.Show(line);
            }


            File.AppendAllText(@"savefile.txt", line + Environment.NewLine);
            string result = line;
           // MessageBox.Show(line);


        }

This does not work.

Mark Baijens
  • 13,028
  • 11
  • 47
  • 73

2 Answers2

4

Strings are immutable in c#

therefore have to replace

  line.Replace("Object", " ");

with

line = line.Replace("Object", String.Empty);

Edit

as slaven-hvar said you cannot change foreach item therefore you to do change to "normal" for loop

for (int i = 0; i < lines.Length; i++)
{
     lines[i] = lines[i].Replace("Object", String.Empty);
}
styx
  • 1,852
  • 1
  • 11
  • 22
1

Use a for loop instead of a foreach loop because line = line.Replace("Object", String.Empty) will not compile because line is a foreach iteration variable. Instead of line = line.Replace("Object", String.Empty) use lines[i]=lines[i].Replace("Object", String.Empty); in a for loop:

string[] lines = File.ReadAllLines(@"pathtofile");
int Object = 0;
for (int i = 0; i < lines.Length; i++)
{
    if (lines[i].Contains("Object"))
    {
        MessageBox.Show("contain!");
        dsObject++;
    }

    if (Object == 1)
    {
        lines[i]=lines[i].Replace("Object", String.Empty);
        MessageBox.Show(lines[i]);
    }

    File.AppendAllText(@"savefile.txt", lines[i] + Environment.NewLine);
    string result = lines[i];
}

If you want your code to be shorter you can use this LINQ solution:

var result = lines.Select(x => x.Replace("Object", String.Empty)).ToList();
result.ForEach(line=>File.AppendAllText(@"savefile.txt", line + Environment.NewLine));
Slaven Tojić
  • 2,945
  • 2
  • 14
  • 33
  • 1
    The linq proposal would scan the data twice, for large data would not be a good advice, but could be modified fo use linq and do just one (doing the replacement inside the `.Foreach`). – Cleptus Apr 10 '18 at 10:14