Reading Text File using .NET

[Migrated content. Thread originally posted on 16 January 2012]


Is there "a clever" .NET way to read a Windows .TXT file thats been created using say "NOTEPAD.EXE"

So my TXT file would contain 30 lines of varying bits of text?

Thanks in advance for any help.

Kind regards

Neil Willby.
  • Verified Answer

    Hi Neil,

    If what you mean by "clever" is using the .NET framework then you should look at the System.IO namespace and classes like StreamReader and File.


          $set ilusing"System.IO"
           program-id. Program1 as "testreadtext.Program1".
           data division.
           working-storage section.
           01 sr           type StreamReader.
           01 wsLine       string.
           01 wsException  type Exception.
           procedure division.

                *> Create an instance of StreamReader to read from a file.
                set sr to new type StreamReader("testfile.txt")
                *> Read and display lines from the file until the end of
                *> the file is reached.
                 perform until exit
                    set wsLine to sr::ReadLine
                    if wsLine = null
                       exit perform   *>EOF reached
                       display wsLine
               catch wsException
                *> Let the user know what went wrong.
                 display "The file could not be read:"
                 display wsException::Message
               invoke sr::Close

    I personally don't find that to be any more clever or easier than using COBOL I-O statements like:

    open input textfile

    read textfile
       at end
          display "done"

    but that's just me :-)
  • I prefer...

           01 #lines string occurs any.

           set #lines to type System.IO.File::ReadAllLines("debug.txt")