14 Replies - 970 Views - Last Post: 21 January 2013 - 02:17 PM Rate Topic: -----

#1 Ravenclaw572  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 21-January 13

System.Net.WebException Error in Visual Basic

Posted 21 January 2013 - 09:21 AM

I've been getting an error with my code, and I'm not exactly sure as to how I can fix it. Here's my code:
Imports System.Net
Public Class Form1
    Dim streamer As IO.StreamReader
    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Dim instance As WebClient = New WebClient
        Dim address As String = "https://my.file.here"
        Dim returnValue As String
        returnValue = instance.DownloadString(address)
        TextBox1.Text = returnValue
        Dim file As String = Application.StartupPath & "/numbers.txt"
        My.Computer.Network.DownloadFile("https://my.file.here", Application.StartupPath & "/numbers.txt", "", "", True, 100, True)
        streamer = IO.File.OpenText(Application.StartupPath & "/numbers.txt")
        Dim mystring() As String = streamer.ReadToEnd.Split(vbNewLine)
        ListBox1.Items.AddRange(mystring)
    End Sub
End Class


Basically, it gets a set of numbers off of my Dropbox, and reads them. It works fine, until I click the button a second time. Then I get this error: "An exception occurred during a WebClient request." It also says the file is in use. Thanks for any and all help! :)

Is This A Good Question/Topic? 0
  • +

Replies To: System.Net.WebException Error in Visual Basic

#2 maj3091  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 300
  • View blog
  • Posts: 1,770
  • Joined: 26-March 09

Re: System.Net.WebException Error in Visual Basic

Posted 21 January 2013 - 10:16 AM

This is VB.Net code and not VB6, that being said, should you not have to close the file after you have finished reading it?
Was This Post Helpful? 1
  • +
  • -

#3 Ravenclaw572  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 2
  • Joined: 21-January 13

Re: System.Net.WebException Error in Visual Basic

Posted 21 January 2013 - 10:28 AM

Sorry, I wasn't sure what it was. I thought it was VB8 or VB10 for the Visual Studio Version. Anyways, how could I close it? The file, that is?
Was This Post Helpful? 0
  • +
  • -

#4 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 9087
  • View blog
  • Posts: 34,134
  • Joined: 12-June 08

Re: System.Net.WebException Error in Visual Basic

Posted 21 January 2013 - 10:32 AM

Moving to VB.NEt
Was This Post Helpful? 0
  • +
  • -

#5 maj3091  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 300
  • View blog
  • Posts: 1,770
  • Joined: 26-March 09

Re: System.Net.WebException Error in Visual Basic

Posted 21 January 2013 - 10:58 AM

I'm not that familiar with .Net just yet, but isn't there a streamreader.close method?
Was This Post Helpful? 0
  • +
  • -

#6 modi123_1  Icon User is online

  • Suitor #2
  • member icon



Reputation: 9087
  • View blog
  • Posts: 34,134
  • Joined: 12-June 08

Re: System.Net.WebException Error in Visual Basic

Posted 21 January 2013 - 11:01 AM

Even better - .dispose!
Was This Post Helpful? 0
  • +
  • -

#7 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3358
  • View blog
  • Posts: 11,371
  • Joined: 12-December 12

Re: System.Net.WebException Error in Visual Basic

Posted 21 January 2013 - 11:10 AM

Even better would be to use a Using block, then you don't have to worry about closing at all:

Using streamer As IO.StreamReader =
    IO.File.OpenText(Application.StartupPath & "/numbers.txt")

End Using


Although, if you are just going to read the entire content then I suppose it could be considered unnecessary.

This post has been edited by andrewsw: 21 January 2013 - 11:14 AM

Was This Post Helpful? 1
  • +
  • -

#8 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3358
  • View blog
  • Posts: 11,371
  • Joined: 12-December 12

Re: System.Net.WebException Error in Visual Basic

Posted 21 January 2013 - 11:22 AM

You could even use an implicit StreamReader and avoid the issue altogether:

Dim mystring() As String = IO.File.OpenText(Application.StartupPath & 
    "/numbers.txt").ReadToEnd.Split(vbNewLine)

This post has been edited by andrewsw: 21 January 2013 - 11:25 AM

Was This Post Helpful? 0
  • +
  • -

#9 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 991
  • View blog
  • Posts: 971
  • Joined: 30-September 10

Re: System.Net.WebException Error in Visual Basic

Posted 21 January 2013 - 11:47 AM

Yep, a using statement is the best way to go here. A using statement ensures Dispose() is called on the StreamReader when execution leaves the using block.

Quote

You could even use an implicit StreamReader and avoid the issue altogether:


You still own the StreamReader in the case of File.OpenText(), and as such need to call Dispose() to clean up after yourself to avoid problems like that described in the OP. EDIT 2: File.OpenText() is simply a factory method that creates a StreamReader object, and returns it to you.

EDIT 1:

Quote

Although, if you are just going to read the entire content then I suppose it could be considered unnecessary.


I'm not sure what you mean there. If you don't call Dispose() on the StreamReader, the file handle won't get released (at least until the underlying FileStream object's finalizer is run by the garbage collector, which technically may never happen), so you should always call Dispose().

This post has been edited by CodingSup3rnatur@l-360: 12 January 2014 - 02:05 PM

Was This Post Helpful? 0
  • +
  • -

#10 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3358
  • View blog
  • Posts: 11,371
  • Joined: 12-December 12

Re: System.Net.WebException Error in Visual Basic

Posted 21 January 2013 - 12:05 PM

Quote

I'm not sure what you mean there.


I mean that it might seem (to some) unnecessary to do (pseudo-code):

Using StreamReader
   ReadToEnd    'only single statement here
End Using

' rather than 
StreamReader = ...
ReadToEnd
StreamReader.Close()


It's not a big deal. Personally, I'm happy to use Using even for a single statement. [Deciding when and if to Close/Dispose a resource is a nuisance, which Using makes a non-issue.]

My code in post 8 surely creates, and disposes of, an implicit stream in one line?!
Was This Post Helpful? 0
  • +
  • -

#11 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 991
  • View blog
  • Posts: 971
  • Joined: 30-September 10

Re: System.Net.WebException Error in Visual Basic

Posted 21 January 2013 - 12:16 PM

Oh, I see. In that case, a using statement has the added advantage of limiting the scope of the StreamReader as much as possible. More importantly, in the example where you just use Close(), if ReadToEnd() throws an exception, the StreamReader will be left undisposed, and the file handle will be leaked.

Quote

My code in post 8 surely creates, and disposes of, an implicit stream in one line?!


No. It creates it, and returns it to you. You then use it, and split the read string into lines, but at no point in that sequence does Dispose() get called on it. Where do you think the Dispose() call would come from, just out of interest? :)

This post has been edited by CodingSup3rnatur@l-360: 21 January 2013 - 12:35 PM

Was This Post Helpful? 0
  • +
  • -

#12 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3358
  • View blog
  • Posts: 11,371
  • Joined: 12-December 12

Re: System.Net.WebException Error in Visual Basic

Posted 21 January 2013 - 12:43 PM

Quote

More importantly, in the example where you just use Close(), if ReadToEnd() throws an exception, the StreamReader will be left undisposed, and the file handle will be leaked.


If there were an Exception it is unhandled anyway so, yes, my 2nd pseudo-code :)/>/> should include a Try..(Catch)..Finally block.

Dim mystring() As String = IO.File.OpenText(Application.StartupPath & 
    "/numbers.txt").ReadToEnd.Split(vbNewLine)


This returns an array of strings. I may be wrong(?) but I believe that the Stream it uses is created, and disposed of, implicitly: a conduit, if you like.

I don't mind be wrong; perhaps you have a link for further information?

This post has been edited by andrewsw: 21 January 2013 - 12:52 PM

Was This Post Helpful? 0
  • +
  • -

#13 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 991
  • View blog
  • Posts: 971
  • Joined: 30-September 10

Re: System.Net.WebException Error in Visual Basic

Posted 21 January 2013 - 01:28 PM

Quote

If there were an Exception it is unhandled anyway so, yes, my 2nd pseudo-code


Not necessarily, the calling method could handle the exception (not in the case where the code is in a button click event handler method like in the OP though, obviously), and program execution will continue, with the file handle leaked. The using statement avoids this as it is compiled as a try-finally. Your pseudo-code didn't indicate that you were suggesting writing your own try-finally explicitly :)

Anyway, you are right. You can write your own try-finally, or use a using block. The two are equivalent :)

Quote

If don't mind be wrong; perhaps you have a link for further information?


I don't see how putting that sequence of method calls on a single line, as opposed to splitting them across multiple lines, would change the behavior of the code.

I cannot find any links about this specific scenario. The best way to settle this is a quick test. You could try something crude like this:

 Sub Main()
        Const FILE_PATH As String = "Test.txt"
        Using w As New StreamWriter(FILE_PATH) 'create file
            w.WriteLine("TEST") 'write to it
        End Using

        Dim lines() As String = File.OpenText(FILE_PATH) _
                                    .ReadToEnd() _
                                    .Split(New String() {vbNewLine}, StringSplitOptions.None) 'create StreamReader, read contents of file, split into lines.

        Dim wr As New StreamWriter(FILE_PATH) 'this line will likely fail

        Console.ReadKey(True)
    End Sub



Trying to open a write stream to the file after reading from the file without disposing of the StreamReader will throw an exception saying the file is in use.

After that, try explicitly calling Dispose() on the StreamReader object returned by File.OpenText() before instantiating the StreamWriter, and the code should run to completion successfully.

This post has been edited by CodingSup3rnatur@l-360: 21 January 2013 - 01:43 PM

Was This Post Helpful? 1
  • +
  • -

#14 andrewsw  Icon User is online

  • Fire giant boob nipple gun!
  • member icon

Reputation: 3358
  • View blog
  • Posts: 11,371
  • Joined: 12-December 12

Re: System.Net.WebException Error in Visual Basic

Posted 21 January 2013 - 01:55 PM

Mmm @ CodingSup3rnatur@l-360 - seems you are right :smartass:.
I'm 96% convinced..

Why would MS allow me to write, compile and run this code, if I can't Dispose of the (unreferenced) Stream..
Was This Post Helpful? 0
  • +
  • -

#15 CodingSup3rnatur@l-360  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 991
  • View blog
  • Posts: 971
  • Joined: 30-September 10

Re: System.Net.WebException Error in Visual Basic

Posted 21 January 2013 - 02:17 PM

Well, language/compiler designers can only go so far in stopping us shooting ourselves in the foot :).

The fact that File.OpenText() returns a StreamReader object (of which implements IDisposable) should be our clue that Dispose() will need to be called on the returned object.

Your code is exactly equivalent, minus a method call (and a null check that said method contains), to this:

Dim mystring() As String =  New StreamReader(Application.StartupPath & "/numbers.txt").ReadToEnd.Split(vbNewLine)



Clearly, we have created the StreamReader, and so it is our responsibility to call Dispose() on it.

This post has been edited by CodingSup3rnatur@l-360: 21 January 2013 - 02:21 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1