DEV Community

Cover image for How to Use curl in .NET (VB.NET)
IronSoftware
IronSoftware

Posted on

How to Use curl in .NET (VB.NET)

How to Use curl in .NET (VB.NET) - including.NET Framework and.NET 10.

VB.NET developers can use CurlDotNet to execute curl commands directly in their code. The library works perfectly with VB.NET's async/await syntax and provides a straightforward way to make HTTP requests.

Installing CurlDotNet

Add the NuGet package to your VB.NET project:

<ItemGroup>
  <PackageReference Include="CurlDotNet" Version="1.0.0" />
</ItemGroup>
Enter fullscreen mode Exit fullscreen mode

Or via Package Manager Console:

Install-Package CurlDotNet
Enter fullscreen mode Exit fullscreen mode

Basic Usage

Here's a simple example in VB.NET:

Imports CurlDotNet
Imports System.Threading.Tasks

Module Program
    Async Function Main(args As String()) As Task(Of Integer)
        Dim result = Await Curl.ExecuteAsync("curl https://api.github.com/users/octocat")

        Console.WriteLine($"Status: {result.StatusCode}")
        Console.WriteLine($"Body: {result.Body}")

        Return 0
    End Function
End Module
Enter fullscreen mode Exit fullscreen mode

Simple GET Request

Imports CurlDotNet
Imports System.Threading.Tasks

Module Program
    Async Function Main(args As String()) As Task(Of Integer)
        Dim result = Await Curl.ExecuteAsync("curl https://jsonplaceholder.typicode.com/posts/1")

        If result.IsSuccess Then
            Console.WriteLine($"Response: {result.Body}")
        Else
            Console.WriteLine($"Error: {result.StatusCode}")
        End If

        Return 0
    End Function
End Module
Enter fullscreen mode Exit fullscreen mode

POST Requests

Here's how to make POST requests:

Imports CurlDotNet
Imports System.Threading.Tasks

Module Program
    Async Function Main(args As String()) As Task(Of Integer)
        Dim command = "curl -X POST https://jsonplaceholder.typicode.com/posts " &
                      "-H 'Content-Type: application/json' " &
                      "-d '{""title"":""My Post"",""body"":""Content"",""userId"":1}'"

        Dim result = Await Curl.ExecuteAsync(command)

        If result.IsSuccess Then
            Console.WriteLine($"Created: {result.StatusCode}")
            Console.WriteLine($"Response: {result.Body}")
        End If

        Return 0
    End Function
End Module
Enter fullscreen mode Exit fullscreen mode

Working with JSON

VB.NET can work with JSON using standard .NET JSON libraries:

Imports CurlDotNet
Imports System.Text.Json
Imports System.Threading.Tasks

Public Class User
    Public Property Login As String
    Public Property Name As String
    Public Property PublicRepos As Integer
End Class

Module Program
    Async Function Main(args As String()) As Task(Of Integer)
        Dim result = Await Curl.ExecuteAsync("curl https://api.github.com/users/octocat")

        If result.IsSuccess Then
            Dim user = JsonSerializer.Deserialize(Of User)(result.Body)
            Console.WriteLine($"User: {user.Name}")
            Console.WriteLine($"Repos: {user.PublicRepos}")
        End If

        Return 0
    End Function
End Module
Enter fullscreen mode Exit fullscreen mode

Authentication

Basic Authentication

Imports CurlDotNet
Imports System.Threading.Tasks

Module Program
    Async Function Main(args As String()) As Task(Of Integer)
        Dim result = Await Curl.ExecuteAsync("curl -u username:password https://api.example.com/protected")

        If result.IsSuccess Then
            Console.WriteLine(result.Body)
        End If

        Return 0
    End Function
End Module
Enter fullscreen mode Exit fullscreen mode

Bearer Token

Imports CurlDotNet
Imports System.Threading.Tasks

Module Program
    Async Function Main(args As String()) As Task(Of Integer)
        Dim command = "curl https://api.example.com/protected " &
                      "-H 'Authorization: Bearer YOUR_TOKEN'"

        Dim result = Await Curl.ExecuteAsync(command)

        If result.IsSuccess Then
            Console.WriteLine(result.Body)
        End If

        Return 0
    End Function
End Module
Enter fullscreen mode Exit fullscreen mode

Error Handling

VB.NET's exception handling works with CurlDotNet:

Imports CurlDotNet
Imports CurlDotNet.Exceptions
Imports System.Threading.Tasks

Module Program
    Async Function Main(args As String()) As Task(Of Integer)
        Try
            Dim result = Await Curl.ExecuteAsync("curl https://api.github.com/users/octocat")
            Console.WriteLine($"Success: {result.Body}")
        Catch ex As CurlDnsException
            Console.WriteLine($"DNS error: {ex.Message}")
        Catch ex As CurlTimeoutException
            Console.WriteLine($"Timeout: {ex.Message}")
        Catch ex As CurlHttpException
            Console.WriteLine($"HTTP {ex.StatusCode}: {ex.Message}")
        Catch ex As CurlException
            Console.WriteLine($"Error: {ex.Message}")
        End Try

        Return 0
    End Function
End Module
Enter fullscreen mode Exit fullscreen mode

File Operations

Downloading Files

Imports CurlDotNet
Imports System.Threading.Tasks

Module Program
    Async Function Main(args As String()) As Task(Of Integer)
        Dim result = Await Curl.ExecuteAsync("curl -o image.png https://example.com/image.png")

        Console.WriteLine($"Downloaded {result.BinaryData.Length} bytes")

        Return 0
    End Function
End Module
Enter fullscreen mode Exit fullscreen mode

Uploading Files

Imports CurlDotNet
Imports System.Threading.Tasks

Module Program
    Async Function Main(args As String()) As Task(Of Integer)
        Dim command = "curl -X POST https://api.example.com/upload " &
                      "-F 'file=@C:\path\to\document.pdf' " &
                      "-F 'description=My Document' " &
                      "-H 'Authorization: Bearer YOUR_TOKEN'"

        Dim result = Await Curl.ExecuteAsync(command)

        If result.IsSuccess Then
            Console.WriteLine("File uploaded successfully")
        End If

        Return 0
    End Function
End Module
Enter fullscreen mode Exit fullscreen mode

Real-World Example: GitHub API

Here's a complete VB.NET example:

Imports CurlDotNet
Imports System.Text.Json
Imports System.Threading.Tasks
Imports System.Environment

Public Class GitHubUser
    Public Property Login As String
    Public Property Name As String
    Public Property PublicRepos As Integer
End Class

Public Class Repository
    Public Property Name As String
    Public Property FullName As String
    Public Property Private As Boolean
End Class

Module Program
    Async Function Main(args As String()) As Task(Of Integer)
        Dim token = GetEnvironmentVariable("GITHUB_TOKEN")

        ' Get user information
        Dim userCommand = "curl https://api.github.com/user " &
                          "-H 'Accept: application/vnd.github.v3+json' " &
                          "-H 'Authorization: token " & token & "'"

        Dim userResult = Await Curl.ExecuteAsync(userCommand)

        If userResult.IsSuccess Then
            Dim user = JsonSerializer.Deserialize(Of GitHubUser)(userResult.Body)
            Console.WriteLine($"Logged in as: {user.Login}")
            Console.WriteLine($"Name: {user.Name}")
            Console.WriteLine($"Public repos: {user.PublicRepos}")
        End If

        ' List repositories
        Dim reposCommand = "curl https://api.github.com/user/repos " &
                           "-H 'Accept: application/vnd.github.v3+json' " &
                           "-H 'Authorization: token " & token & "'"

        Dim reposResult = Await Curl.ExecuteAsync(reposCommand)

        If reposResult.IsSuccess Then
            Dim repos = JsonSerializer.Deserialize(Of Repository())(reposResult.Body)
            Console.WriteLine($"{vbCrLf}You have {repos.Length} repositories:")
            For Each repo In repos
                Console.WriteLine($"  - {repo.FullName}")
            Next
        End If

        Return 0
    End Function
End Module
Enter fullscreen mode Exit fullscreen mode

Using the Fluent Builder API

The fluent builder API also works in VB.NET:

Imports CurlDotNet
Imports CurlDotNet.Core
Imports System.Threading.Tasks

Module Program
    Async Function Main(args As String()) As Task(Of Integer)
        Dim result = Await CurlRequestBuilder.
            Post("https://api.example.com/users").
            WithHeader("Content-Type", "application/json").
            WithJson(New With {.name = "John", .email = "john@example.com"}).
            WithTimeout(TimeSpan.FromSeconds(30)).
            FollowRedirects().
            ExecuteAsync()

        If result.IsSuccess Then
            Console.WriteLine($"Status: {result.StatusCode}")
        End If

        Return 0
    End Function
End Module
Enter fullscreen mode Exit fullscreen mode

Conclusion

CurlDotNet works great with VB.NET! You can paste curl commands directly into your VB.NET code, making API integration straightforward and easy. The async/await syntax in VB.NET pairs perfectly with CurlDotNet's async methods.

Try it in your VB.NET project - you'll find it makes HTTP requests much simpler!


Learn More:

Top comments (0)