Posts

Showing posts with the label Loops

C#: Looping Through Lines Of Multiline String

Answer : I suggest using a combination of StringReader and my LineReader class, which is part of MiscUtil but also available in this StackOverflow answer - you can easily copy just that class into your own utility project. You'd use it like this: string text = @"First line second line third line"; foreach (string line in new LineReader(() => new StringReader(text))) { Console.WriteLine(line); } Looping over all the lines in a body of string data (whether that's a file or whatever) is so common that it shouldn't require the calling code to be testing for null etc :) Having said that, if you do want to do a manual loop, this is the form that I typically prefer over Fredrik's: using (StringReader reader = new StringReader(input)) { string line; while ((line = reader.ReadLine()) != null) { // Do something with the line } } This way you only have to test for nullity once, and you don't have to think about a do/while...

Batch Script Loop

Answer : for /l is your friend: for /l %x in (1, 1, 100) do echo %x Starts at 1, steps by one, and finishes at 100. Use two % s if it's in a batch file for /l %%x in (1, 1, 100) do echo %%x (which is one of the things I really really hate about windows scripting) If you have multiple commands for each iteration of the loop, do this: for /l %x in (1, 1, 100) do ( echo %x copy %x.txt z:\whatever\etc ) or in a batch file for /l %%x in (1, 1, 100) do ( echo %%x copy %%x.txt z:\whatever\etc ) Key: /l denotes that the for command will operate in a numerical fashion, rather than operating on a set of files %x is the loops variable (starting value, increment of value, end condition[inclusive] ) And to iterate on the files of a directory: @echo off setlocal enableDelayedExpansion set MYDIR=C:\something for /F %%x in ('dir /B/D %MYDIR%') do ( set FILENAME=%MYDIR%\%%x\log\IL_ERROR.log echo =========================== Search in !FILE...