简体   繁体   中英

inserting into index location of a text file if a string does exist inside the line, if the string doesn't exist, still write line as it was

The program is supposed to look for a string in a line, and if it finds the string, it will make the inserts after meeting the condition inside the textfile. Currently, when I run this program it is now simply giving me a blank console. Previously, I had it just reading all the lines properly and could make inserts only if I remove them first but it messed the indexing up and ultimately did not give me the result I wanted. The logic is fairly straightforward, if you see any problems please share your thoughts. Please and thanks. I am very confused why this is having problems and not working.

using System.IO;
using System.Globalization;
using System.Diagnostics;
using System.Text;
using System.Linq;
using System.Linq.Expressions;

namespace Masker 
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine();
            string path = @"\file1.txt";
            ReadLines(path)

        }
        public static void ReadLines(string path) 
        {
            int counter = 0;
            var text = new StringBuilder();
            foreach (string s in File.ReadAllLines(path)) 
            {
                counter += 1;
                if (s.Contains("000INDEX"))
                {
                    text.AppendLine(s.Insert(60, "#")); 
                } 
                else if (s.Contains("001PRTBNR")) 
                {
                    text.AppendLine(s.Insert(60, "#").Insert(119,"#").Insert(120,"#").Insert(121, "#"));
                    
                };
                text.AppendLine(s);
                //Console.Write(text.ToString());
            }
            Console.Write(text.ToString());
        }
       

    }
}

The last two blocks of your if/else statement will never be executed. If the execution reaches the third check

else if (s.Contains("000INDEX"))

that will always be true. Because if it wasn't, then the first check

if (.s.Contains("000INDEX"))

would have already been true.

But the biggest problem is that if the line contains "000INDEX", your while loop becomes and infinite loop. You never leave it. That is probably the reason why you end up with a blank console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM