Results 1 to 1 of 1

Thread: [2005] IO: Handling textfiles the easy way, no StreamReaders/Writers required.

  1. #1

    Thread Starter
    Fanatic Member arsmakman's Avatar
    Join Date
    Dec 2001
    Location
    Leiden, Netherlands.
    Posts
    719

    Smile [2005] IO: Handling textfiles the easy way, no StreamReaders/Writers required.

    Greetings fellow programmer,

    Visual Basic .NET 2003 was quite horrible when it came to reading/writing files, you had to load StreamReader or StreamWriter then close it again and it all became very complicated, resulting in many file access errors if your code wasn't perfect.
    With VB 2005 this all got much easier with the new File-object, sadly many people don't know about this.
    So, here are some basic examples for reading, writing and appending to/from textfiles usinf the File-object.
    VB Code:
    1. 'Read a file:
    2. Dim sFileContent As String = IO.File.ReadAllText(sFilename)
    3. Debug.Print sFileContent
    4.  
    5. 'Read a file line-by-line:
    6. 'First method (easy to use when file is only needed for reading)
    7. For Each sLine As String In IO.File.ReadAllLines(sFilename)
    8.     Debug.Print sLine
    9. Next
    10. 'Second method (easy to use when you want to write a file using this data)
    11. Dim sLines() As String = IO.File.ReadAllLines(sFilename)
    12.  
    13. 'Read a file byte-by-byte:
    14. For Each btByte As Byte In IO.File.ReadAllBytes(sFilename)
    15.     Debug.Print btByte.ToString
    16. Next
    17. Dim btBytes() As Byte = IO.File.ReadAllBytes(sFilename)
    18.  
    19. 'Write a file:
    20. IO.File.WriteAllText(sFilename, sFileContent)
    21.  
    22. 'Write a file line-by-line:
    23. IO.File.WriteAllLines(sFilename, sLines)
    24.  
    25. 'Write a file byte-by-byte:
    26. IO.File.WriteAllBytes(sFilename, btBytes)
    27.  
    28. 'Append to a file:
    29. IO.File.Append(sFilename, sFileContent)
    If your file uses non-UTF-8 encoding, you can add the encoding after any of the functions, using 'System.Text.Encoding.[Encoding's Name]'.

    While still talking IO, also check out the all new IO.Directory and IO.Path-objects, they make those DirectoryInfo- and FileInfo-objects obsolete for some common situations.

    Greetings and happy programming,

    Smakkie.
    Last edited by arsmakman; Aug 22nd, 2006 at 10:27 AM.
    No matter how fool-proof your program is, there will always be a better fool.

    Was a post helpful to you? Rate it!

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width