foreach for Class copies



  • How do you arrange foreach for Class FileInfo copies? Trying to do this:

    FileInfo[] fileInfos = directoryInfo.GetFiles(); //создаём массив из fileInfo всех файлов
    FileInfo file = new FileInfo(fileInfos[number].FullName); //экземпляр fileInfos, 
                                                      //над которым будут проводиться действия
    foreach (FileInfo file in fileInfos) //для каждого файла из тех, что в директории
    {
       StreamReader //читаем файл
       if (...) //условие к содержимому файла
       doSomething //если условие выполняется, делаем что-нибудь
    }
    

    But obviously, it doesn't work out because, in fact, inside foreach I'm reapplying the already existing variable. filewhich makes it impossible to use it further. I've been overfloating some sort of tricks, but it's mostly used. foreach There are no problems with the masses or collections created manually. I've done my best to comment on this code outline to make it clearer than I'm trying to do. I can't figure out how to do this if you can.



  • If every file in 'c'temp' has to process the lines:

    foreach(var file in System.IO.Directory.EnumerateFiles(@"c:\temp")) {
        var lines = System.IO.File.ReadLines(file);
        // ...
    }
    

    EnumerateFiles and ReadLines are returning IEnumerable (i.e., the data are not stored in total) and therefore in memory. c:\temp There may be any number of files, and the files themselves may contain millions of lines -- OutOfMemoryException will not arise.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2