Skip to content

Refactor VB's Application Framework Network Class #9807

Open

Description

The class Microsoft.VisualBasic.Devices.Network, which is part of the Visual Basic Application Framework, is based on the obsoleted WebClient class.

We need to modernize this part of the Application Framework to avoid breaking changes, should the WebClient class no longer be included in future versions of .NET.

This should be done in the .NET 9-time frame.

This also addresses #3936.

Here is a potential general approach, which uses HttpClient instead of WebClient.
(!not tested, and my last Web-dev-experiences is quite a while, so, please double-check me here!)

Imports System.IO
Imports System.Net
Imports System.Net.Http

Public Class Network

    Public Async Function DownloadFileWithCredentialsAndProgressAsAStartingPointAsync(
        url As String,
        destinationPath As String,
        credentials As NetworkCredential,
        progress As IProgress(Of Double)) As Task

        Dim handler As New HttpClientHandler() With
        {
            .Credentials = credentials
        }

        Using httpClient As New HttpClient(handler)

            Dim response = Await httpClient.GetAsync(url, HttpCompletionOption.ResponseHeadersRead)
            Dim contentLength = response.Content.Headers.ContentLength

            Using responseStream As Stream = Await response.Content.ReadAsStreamAsync()
                Using fileStream As New FileStream(destinationPath, FileMode.Create, FileAccess.Write, FileShare.None)

                    Dim buffer(8191) As Byte
                    Dim totalBytesRead As Long = 0
                    Dim bytesRead As Integer

                    While (Await responseStream.ReadAsync(buffer, 0, buffer.Length)) > 0
                        Await fileStream.WriteAsync(buffer, 0, bytesRead)
                        totalBytesRead += bytesRead

                        If contentLength.HasValue Then
                            Dim percentage As Double = (CDbl(totalBytesRead) / CDbl(contentLength.Value)) * 100
                            progress.Report(percentage)
                        End If

                    End While
                End Using
            End Using
        End Using
    End Function
End Class
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Labels

🚧 work in progressWork that is current in progressPriority:2Work that is important, but not critical for the releasearea-VisualBasichelp wantedGood issue for external contributors

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions