Results 1 to 5 of 5

Thread: Reading/writing 2d string array from/to file

  1. #1

    Thread Starter
    New Member
    Join Date
    Sep 2011
    Posts
    2

    Reading/writing 2d string array from/to file

    I can write a 1-d string array to file with:

    Dim test() As String = {1, 2, 3, 4, 5}
    File.WriteAllLines("C:\MyFile.txt", test)

    but can't see how to write a 2-d array to file.

    I've tried this:

    Dim test(,) As String = {{1, 2, 3, 4, 5}, {34, 22, 12, 33, 55}}
    Dim myfile = File.CreateText("C:\MyFile.txt")
    Dim row, col As Integer
    For row = 0 To 1
    For col = 0 To 4
    myfile.WriteLine(test(row, col))
    Next
    Next

    which produces a file of 0 bytes.

    What should I be doing?

  2. #2

    Re: Reading/writing 2d string array from/to file

    Try using the System.IO.StreamWriter class instead.

  3. #3
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,422

    Re: Reading/writing 2d string array from/to file

    try this:

    vb Code:
    1. Dim test(,) As String = {{1, 2, 3, 4, 5}, {34, 22, 12, 33, 55}}
    2. IO.File.WriteAllLines("test.txt", Enumerable.Range(0, test.GetLength(0)).Select(Function(i1) String.Join(",", Enumerable.Range(0, test.GetLength(1)).Select(Function(i2) test(i1, i2)).ToArray)).ToArray)

    i've got an example for reading a 2d array somewhere. i'll have a look for it.

  4. #4
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,422

    Re: Reading/writing 2d string array from/to file


  5. #5

    Thread Starter
    New Member
    Join Date
    Sep 2011
    Posts
    2

    Re: Reading/writing 2d string array from/to file

    Quote Originally Posted by .paul. View Post
    try this:

    vb Code:
    1. Dim test(,) As String = {{1, 2, 3, 4, 5}, {34, 22, 12, 33, 55}}
    2. IO.File.WriteAllLines("test.txt", Enumerable.Range(0, test.GetLength(0)).Select(Function(i1) String.Join(",", Enumerable.Range(0, test.GetLength(1)).Select(Function(i2) test(i1, i2)).ToArray)).ToArray)

    i've got an example for reading a 2d array somewhere. i'll have a look for it.
    Many thanks. I'm not sure I understand the code (!) but it works well.

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