Search code examples
.netvb.netstreamreader

StreamReader throws System.IO.FileInfo[] exception when reading files


Every time I try to read a file using a StreamReader, it is throwing the following exception:

System.IO.FileInfo[] cannot be found.

Here is my code:

Dim dinfo As New DirectoryInfo(TextBox1.Text)

Dim files As FileInfo() = dinfo.GetFiles("*.txt", SearchOption.AllDirectories)

Dim sr = New StreamReader(TextBox1.Text & "/" & dinfo.GetFiles.ToString)

Further in my code I have this sample, I don't know if it's relevant but just in case:

Dim dinfo As New DirectoryInfo(TextBox1.Text)

Dim files As FileInfo() = dinfo.GetFiles("*.txt", SearchOption.AllDirectories)

ListBox1.Items.Clear()
For Each file As FileInfo In files
    ListBox1.Items.Add(file.Name)
 Next

I'm trying to pass all the found .txt files to the StreamReader so the StreamReader can read all the found .txt files one by one.


Solution

  • You can't use dinfo.GetFiles.ToString like that. This will return System.IO.FileInfo[] whilst a StreamReader is expecting a path or a stream. I think in this case a path.

    Also rather than concatenating strings together to make a path up consider using Path.Combine. Although in the end I don't think you will actually need this but it's worth reading up on it.

    I would also consider implementing Using when using a StreamReader:

    Sometimes your code requires an unmanaged resource, such as a file handle, a COM wrapper, or a SQL connection. A Using block guarantees the disposal of one or more such resources when your code is finished with them. This makes them available for other code to use.

    Based on your comment, I think what you are after is something like this:

    Dim dinfo As New DirectoryInfo(TextBox1.Text)
    For Each f In dinfo.GetFiles("*.txt", SearchOption.AllDirectories)
        Using sr As New StreamReader(f.FullName)
            While Not sr.EndOfStream
                Debug.WriteLine(sr.ReadLine())
            End While
        End Using
    Next