Thursday, November 26, 2026

Azure Blob storage Example

 In this article, we will learn how to fetch the details from blob storage 


Imports System

Imports System.Diagnostics

Imports System.IO

Imports System.Text


Public Class AzureBlobService


    Private ReadOnly _azCopyPath As String

    Private ReadOnly _containerUrl As String


    Private ReadOnly _clientId As String

    Private ReadOnly _clientSecret As String

    Private ReadOnly _tenantId As String


    Public Sub New(

        azCopyPath As String,

        storageAccount As String,

        containerName As String,

        clientId As String,

        clientSecret As String,

        tenantId As String)


        _azCopyPath = azCopyPath

        _clientId = clientId

        _clientSecret = clientSecret

        _tenantId = tenantId


        _containerUrl =

            "https://" & storageAccount &

            ".blob.core.windows.net/" &

            containerName


        If String.IsNullOrWhiteSpace(clientSecret) Then

            Throw New ArgumentException(

                "Client secret is required.")

        End If


    End Sub


    ' Generate Blob URL

    Private Function GetBlobUrl(

        blobName As String) As String


        If String.IsNullOrWhiteSpace(blobName) OrElse

           blobName.Contains("*") Then


            Throw New ArgumentException(

                "Invalid blob name.")

        End If


        Dim parts As String() = blobName.Split("/"c)


        For i As Integer = 0 To parts.Length - 1

            parts(i) = Uri.EscapeDataString(parts(i))

        Next


        Return _containerUrl & "/" &

               String.Join("/", parts)


    End Function


    ' Upload File

    Public Function UploadFile(

        localPath As String,

        blobName As String) As String


        If Not File.Exists(localPath) Then

            Throw New FileNotFoundException(

                "Source file not found.")

        End If


        Dim arguments As String =

            "copy " &

            Quote(localPath) & " " &

            Quote(GetBlobUrl(blobName)) &

            " --overwrite=true"


        Return ExecuteAzCopy(arguments)


    End Function


    ' Download File

    Public Function DownloadFile(

        blobName As String,

        localPath As String) As String


        Dim folder As String =

            Path.GetDirectoryName(localPath)


        If Not String.IsNullOrEmpty(folder) Then

            Directory.CreateDirectory(folder)

        End If


        Dim arguments As String =

            "copy " &

            Quote(GetBlobUrl(blobName)) & " " &

            Quote(localPath) &

            " --overwrite=true"


        Return ExecuteAzCopy(arguments)


    End Function


    ' Delete File

    Public Function DeleteFile(

        blobName As String) As String


        Dim arguments As String =

            "remove " &

            Quote(GetBlobUrl(blobName)) &

            " --recursive=false"


        Return ExecuteAzCopy(arguments)


    End Function


    ' List Files

    Public Function ListFiles() As String


        Dim arguments As String =

            "list " & Quote(_containerUrl)


        Return ExecuteAzCopy(arguments)


    End Function


    ' Check AzCopy Version

    Public Function GetVersion() As String


        Return ExecuteAzCopy("--version")


    End Function


    ' Quote command arguments

    Private Function Quote(

        value As String) As String


        If value.Contains("""") OrElse

           value.Contains(vbCr) OrElse

           value.Contains(vbLf) OrElse

           value.EndsWith("\") Then


            Throw New ArgumentException(

                "Invalid command argument.")

        End If


        Return """" & value & """"


    End Function


    ' Execute AzCopy

    Private Function ExecuteAzCopy(

        arguments As String) As String


        If Not File.Exists(_azCopyPath) Then

            Throw New FileNotFoundException(

                "AzCopy.exe not found.")

        End If


        Dim output As New StringBuilder()

        Dim errors As New StringBuilder()


        Dim startInfo As New ProcessStartInfo()


        startInfo.FileName = _azCopyPath

        startInfo.Arguments = arguments

        startInfo.UseShellExecute = False

        startInfo.CreateNoWindow = True

        startInfo.RedirectStandardOutput = True

        startInfo.RedirectStandardError = True


        ' Service Principal Authentication

        startInfo.EnvironmentVariables(

            "AZCOPY_AUTO_LOGIN_TYPE") = "SPN"


        startInfo.EnvironmentVariables(

            "AZCOPY_SPA_APPLICATION_ID") = _clientId


        startInfo.EnvironmentVariables(

            "AZCOPY_SPA_CLIENT_SECRET") = _clientSecret


        startInfo.EnvironmentVariables(

            "AZCOPY_TENANT_ID") = _tenantId


        Using proc As New Process()


            proc.StartInfo = startInfo


            AddHandler proc.OutputDataReceived,

                Sub(sender, e)

                    If e.Data IsNot Nothing Then

                        output.AppendLine(e.Data)

                    End If

                End Sub


            AddHandler proc.ErrorDataReceived,

                Sub(sender, e)

                    If e.Data IsNot Nothing Then

                        errors.AppendLine(e.Data)

                    End If

                End Sub


            proc.Start()


            proc.BeginOutputReadLine()

            proc.BeginErrorReadLine()


            proc.WaitForExit()


            If proc.ExitCode <> 0 Then


                Dim errorMessage As String =

                    errors.ToString() &

                    vbCrLf & output.ToString()


                errorMessage =

                    errorMessage.Replace(

                        _clientSecret, "[REDACTED]")


                Throw New Exception(

                    "AzCopy failed. Exit Code: " &

                    proc.ExitCode.ToString() &

                    vbCrLf & errorMessage)


            End If


        End Using


        Return output.ToString().

            Replace(_clientSecret, "[REDACTED]")


    End Function


End Class


Initialiaze:

Dim blobService As New AzureBlobService(

    "C:\Tools\AzCopy\azcopy.exe",

    "mystorageaccount",

    "documents",

    "YOUR-CLIENT-ID",

    Environment.GetEnvironmentVariable(

        "AZURE_CLIENT_SECRET"),

    "YOUR-TENANT-ID"

)


How to call?

Try


    Dim result As String =

        blobService.DownloadFile(

            "sample.pdf",

            "C:\Downloads\sample.pdf")


    MessageBox.Show("Download successful")


Catch ex As Exception


    MessageBox.Show(ex.Message)


End Try



Try


    Dim result As String =

        blobService.DeleteFile("sample.pdf")


    MessageBox.Show("Delete command completed")


Catch ex As Exception


    MessageBox.Show(ex.Message)


End Try



0 comments:

Post a Comment