How to write only # before some lines in a text file?

I have a text file that looks like this:

Rows ... product.people product.people_good product.people_bad product.boy #product.me ... Rows 

I want to put # in front of the product. , and the file should be:

 Rows ... #product.people #product.people_good #product.people_bad #product.boy #product.me ... Rows 

For this, I use the following code:

 string installerfilename = pathTemp + fileArr1; string installertext = File.ReadAllText(installerfilename); var linInst = File.ReadLines(pathTemp + fileArr1).ToArray(); foreach (var txt in linInst) { if (txt.Contains("#product=")) { installertext = installertext.Replace("#product=", "product="); } else if (txt.Contains("product.") && (!txt.StartsWith("#"))) { installertext = installertext.Replace(txt, "#" + txt); } File.WriteAllText(installerfilename, installertext); } 

But this code will do the following:

 Rows ... #product.people ##product.people_good ##product.people_bad #product.boy #product.me ... Rows 

Can anyone explain the way for me? And how can I write only one # in front of these lines?

+5
source share
3 answers

You are currently reading the same text file twice - these are separate lines and once as a whole. Then you rewrite the file as many times as you have lines. All this is broken. I suspect you just want:

 // Note name changes to satisfy .NET conventions // Note: If pathTemp is a directory, you should use Path.Combine string installerFileName = pathTemp + fileArr1; var installerLines = File.ReadLines(installerFileName) .Select(line => line.StartsWith("product=") ? "#" + line : line) .ToList(); File.WriteAllLines(installerFileName, installerLines); 

If you wrote to a different file than the one you read from, you do not need a ToList call.

+5
source

You can split by product and then combine it into a new line:

  // string installerFileText = File.ReadAllText(installerFileName); string installerFileText = @" Rows ... product.people product.people_good product.people_bad product.boy ... Rows"; string[] lines = installerFileText.Split(new string[] { "product." }, StringSplitOptions.None); StringBuilder sb = new StringBuilder(); for (int i = 0; i < lines.Length; i++) sb.Append(((i > 0 && i < lines.Length) ? "#product." : "") + lines[i]); // File.WriteAllText(installerFileName, sb.ToString()); Console.WriteLine(sb.ToString()); Console.ReadKey(); 

Output:

  Rows ... #product.people #product.people_good #product.people_bad #product.boy ... Rows"; 
+2
source
 else if (txt.Contains("product.") && (!txt.StartsWith("#"))) { installertext = installertext.Replace(txt, "#" + txt); } 

Why don't you replace "! Txt.StartsWith (" # ")" with "! Txt.Contains (" # ")"?

Think it will do the trick!

-1
source

Source: https://habr.com/ru/post/1233339/


All Articles