Question

I have this function:

Function WriteTextToFile(ByVal data)
    Dim file As New System.IO.StreamWriter("E:\storage.txt")
    file.WriteLine(data)
    file.Close()
End Function

I have been trying to adjust it so that the filepath becomes a variable I can pass to allow for multiple storage files. Something like this:

Function AppendTextToFile(ByVal data, ByVal path)

        Dim file As New System.IO.StreamWriter(path, True)
        file.WriteLine(data)
        file.Close()

    End Function

However while function 1 works, function 2 doesn't - I get this unhelpful error:

Overload resolution failed because no accessible 'New' can be called without a narrowing conversion:
    'Public Sub New(path As String)': Argument matching parameter 'path' narrows from 'Object' to 'String'.
    'Public Sub New(stream As System.IO.Stream)': Argument matching parameter 'stream' narrows from 'Object' to 'System.IO.Stream'. C:\Users\films ratings\films ratings\Form1.vb

I normally work in PHP and I've never seen an error of this nature before. What does it mean and can I re-write the function to get what I want?

Was it helpful?

Solution

Declare the variable path as a String type and you'll be fine.

The compiler is not able to determine what overload of the constructor should be used because you declared the path parameter as Object (that's the default when you don't specify otherwise).

Instead, you should declare your second function like this:

Function AppendTextToFile(ByVal data, ByVal path As String)

OTHER TIPS

You're passing the path (and data) parameters as an object. By simply always strongly typing the variables the error here will disappear.

Function AppendTextToFile(ByVal data As String, ByVal path As String)

    Dim file As New System.IO.StreamWriter(path, True)
    file.WriteLine(data)
    file.Close()

End Function
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top