0

I have code that is supposed to replace the word "simple" with the word "word" within all text files in the given directly, but I do not know what to correct in order for the code to work.

static void Main(string[] args)
        {
            // Например, получаем все файлы определённого типа в заданной директории.
            string[] fileList = Directory.GetFiles(@"C:/Users/Users/Desktop/a/","*.txt");
            foreach (var filePath in fileList) // Для каждого пути файла...
            {
                for (int i = 0; i < filePath.Length; i++)
                {
                    var lines = File.ReadAllText(filePath);
                    lines = lines.Replace("simple", "word");
                    File.WriteAllText(filePath, lines);
                }
            }
        }
Sophie Coyne
  • 1,018
  • 7
  • 16
komra23
  • 107
  • 8

2 Answers2

1

I imagine that your code is taking a while because of the line

for (int i = 0; i < filePath.Length; i++)

which makes the code occur for each individual character within each file. Simply remove it like so.

static void Main(string[] args)
{

    string[] fileList = Directory.GetFiles(@"C:/Users/Users/Desktop/a/","*.txt");
    foreach (var filePath in fileList) // Для каждого пути файла...
    {
        var lines = File.ReadAllText(filePath);
        lines = lines.Replace("simple", "word");
        File.WriteAllText(filePath, lines);
    }
}
Sophie Coyne
  • 1,018
  • 7
  • 16
0

Your double for loop reads "for each file, do something for each character in the file's path name"

I highly doubt that is what you want since you don't use the i variable anywhere

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245