【问题标题】:Uploading all Sub-Directories and Files to an Azure Storage Account File Share Using VB.NET使用 VB.NET 将所有子目录和文件上传到 Azure 存储帐户文件共享
【发布时间】:2020-01-20 23:50:35
【问题描述】:

如何将我 PC 上根目录中的所有文件和子目录上传到我的 Azure 存储帐户文件共享(文件,而不是 blob)? 我的想法是我想有效地“克隆”我的 PC 或硬盘上存在的所有文件和目录结构,并将它们上传到我的 Azure 文件共享中。

Dominic Whitham's Online Graphic Portfolio

【问题讨论】:

    标签: azure fileshare azure-storage-account


    【解决方案1】:

    我需要将数千个文件及其文件夹上传到我的 Azure 存储帐户文件共享(文件,而不是 blob)。所以我创建了一个简单的 PC 应用程序,它可以让我在我的 PC(或附加的硬盘驱动器)上选择一个文件夹,单击一个按钮,瞧!然后,这些文件和目录很容易“克隆”到我在云中的 Azure 文件共享位置。

    要开始使用,您需要在 Visual Studio 中创建一个新项目。我正在使用 VS 2017。

    第 1 步:创建新的 Windows 窗体应用

    第 2 步:我们需要添加一个 NuGet 包,名为 WindowsAzure.Storage (v. 9.3.3),因此请转到 Project-->Manage NuGet Packages。单击浏览选项卡并搜索 WindowsAzure.Storage。然后点击“安装”。

    第 3 步:向您的项目添加一个新类。然后复制/粘贴以下代码,其中包含繁重的上传文件所需的功能...

    步骤 3a:重要;请务必将“yourStorageAccountName”和“yourStorageAccountKey”值替换为代表您的 Azure 文件存储帐户的有效值。

    Imports Microsoft.WindowsAzure.Storage
    Imports System.IO
    Imports Microsoft.WindowsAzure.Storage.File
    
    Public Class AzureStorageUpload
        Private mConnectionString As String = "DefaultEndpointsProtocol=https;AccountName=yourStorageAccountName;AccountKey=yourStorageAccountKey"
    
        Private mUploadFileSize As Long
        Private mUploadFileExtension As String
        Private mCloudFile As CloudFile
    
        Public Sub UploadFileAsFileToAzureStorage(fileShare As String, folderPath As String, fullFilePath As String, originalName As String)
            'Connect to Azure
            Dim storageAccount As CloudStorageAccount = CloudStorageAccount.Parse(mConnectionString)
    
            ' Create a reference to the file client.
            Dim CloudFileClient = storageAccount.CreateCloudFileClient()
            Dim share As CloudFileShare = CloudFileClient.GetShareReference(fileShare)
            If share.Exists = True Then
                Dim rootDir As CloudFileDirectory = share.GetRootDirectoryReference()
                Dim cfd As CloudFileDirectory = share.GetRootDirectoryReference()
                cfd = cfd.GetDirectoryReference(folderPath)
    
                'Create a reference to the filename that you will be uploading
                mCloudFile = cfd.GetFileReference(originalName)
    
                'Upload the file to Azure
                mCloudFile.UploadFromFile(fullFilePath)
    
                mUploadFileSize = mCloudFile.Properties.Length
                mUploadFileExtension = Path.GetExtension(mCloudFile.Name)
            End If
    
            share = Nothing
            CloudFileClient = Nothing
            storageAccount = Nothing
        End Sub
    
        Public Sub CreateDirectory(fileShare As String, folder As String)
            'Connect to Azure
            Dim storageAccount As CloudStorageAccount = CloudStorageAccount.Parse(mConnectionString)
    
            ' Create a reference to the file client.
            Dim CloudFileClient = storageAccount.CreateCloudFileClient()
            Dim share As CloudFileShare = CloudFileClient.GetShareReference(fileShare)
    
            If share.Exists = True Then
                Dim cfd As CloudFileDirectory = share.GetRootDirectoryReference()
                cfd = cfd.GetDirectoryReference(folder)
                cfd.CreateIfNotExists()
    
                cfd = Nothing
            End If
    
            share = Nothing
            CloudFileClient = Nothing
            storageAccount = Nothing
        End Sub
    
        Private Function PathOnly(fileName As String) As String
            Dim l As Long
    
            l = InStrRev(fileName, "\")
            If l = 0 Then
                Return fileName
            Else
                Return Mid(fileName, 1, l)
            End If
        End Function
    
        Public Function JobOnly(ByVal MyJob As String) As String
            Dim l As Long
    
            JobOnly = MyJob
            l = InStrRev(JobOnly, "\")
            If l = 0 Then
                Exit Function
            End If
            JobOnly = Mid(JobOnly, l + 1, Len(JobOnly) - l)
    
            l = InStrRev(JobOnly, ".")
            If l = 0 Then
                Exit Function
            Else
                'Eliminate the extension
                JobOnly = Mid(JobOnly, 1, l - 1)
            End If
        End Function
    End Class
    

    第 4 步:在您的 Windows 窗体 (form1) 上,放置以下控件:

    1. TextBox1 应该是一个宽文本框,它将保存所需的路径。 此路径将是所有文件的“根”路径,并且
      将创建并上传到 Azure 文件的子目录 分享。请注意,根文件夹的文件(如果有的话)将 不被枚举,因此不会被复制,但所有的都是
      子目录,它们的子目录和文件都将 “克隆”、上传和复制。
    2. 放置一个按钮,Button1,上面写着“选择文件夹”
    3. 在其下方,放置显示“上传到云端”的 Button2
    4. 在其下方,放置显示“取消”的 Button3
    5. 添加一个 StatusStrip,停靠在底部,并在其中放置一个 名称为“tsData1”的 ToolStripStatusLabel
    6. 添加一个 FolderBrowserDialog 控件,并将其命名为“fbd1”

    第 5 步:现在您可以在表单后面添加代码了:

    Imports System.IO
    
    Public Class Form1
        Private mWorking As Boolean
    
        Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
            ' Select Folder/Directory to Upload
            ' Note:  The idea is that all SubDirectories and Files will be copied (cloned) to your Azure Storage FileShare (as Files, not Blobs)
            Dim DiaResult As DialogResult
            Dim batchFolder As String = "c:\"
    
            With fbd1
                .RootFolder = Environment.SpecialFolder.MyComputer
                .SelectedPath = batchFolder
                .Description = "Select folder to Upload to Azure Storage"
                DiaResult = .ShowDialog()
                If DiaResult <> Windows.Forms.DialogResult.OK Then
                    Exit Sub
                Else
                    TextBox1.Text = .SelectedPath
                End If
            End With
        End Sub
    
        Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
            Dim i As Integer
    
            WaitCursor(True)
            ' Note: Here, I'm searching for all files that have a .png extension.  If you simply want to transfer ALL files within the folders,
            ' just use *.* instead of *.png
            ' Also note that the initial directory's files are NOT enumerated (so if there are FILES in your initial chosen directory, they are NOT copied)
            Dim files = From d In Directory.EnumerateDirectories(TextBox1.Text, "*", SearchOption.AllDirectories)
                        From f In Directory.EnumerateFiles(d, "*.*")
                        Select f
    
            Dim txtFilesArray() As String = files.ToArray()
            WaitCursor(False)
    
            Dim count As Integer = 0
    
            Dim asu As New AzureStorageUpload
    
            ' Get the initial directory which has already been selected
            Dim Prefix As String = LCase(TextBox1.Text)
            Prefix = Replace(Prefix, Path.GetDirectoryName(Prefix), "")
    
            ' Create a log file to record the progress...
            Dim myLog As String = GetAppPath() & "\UploadLog.txt"
    
            ' Your file share goes here.  Be sure everything is lower case
            ' Note that your file share must already exist (use the Azure portal to create your fileshare name)
            Dim yourFileShare As String = "yourfileshare"
    
            Try
                ' This will create your initial directory within your file share
                ' Your intention is that you'll be uploading (cloning) everything, including subdirectories and files,
                ' that currently exist on your PC inside your "starting" folder.
                asu.CreateDirectory(yourFileShare, Prefix)
            Catch ex As Exception
    
            End Try
    
            MsgBox("Ready to begin uploading files...")
    
            Dim sw2 As New StreamWriter(New FileStream(myLog, FileMode.Create, FileAccess.Write))
            Dim startTime As Date = DateAndTime.Now
            sw2.WriteLine("Starting Upload at " & startTime.ToLongTimeString & " on " & startTime.ToLongDateString)
    
            mWorking = True
    
            WaitCursor(True)
            While mWorking = True
                For i = 0 To txtFilesArray.Length - 1
                    Application.DoEvents()
    
                    Dim origPath As String = txtFilesArray(i)
    
                    If File.Exists(origPath) = True Then
                        Dim pathOnly As String = Replace(origPath, TextBox1.Text, "")
                        Dim l As Integer = InStrRev(pathOnly, "\")
    
                        ' Create the path - path must be all lowercase (which it is already)
                        Dim newPath As String = Mid(pathOnly, 2, l - 2)
                        If InStr(newPath, "\") = 0 Then
                            Try
                                asu.CreateDirectory(yourFileShare, Prefix & "\" & newPath)
                            Catch ex As Exception
    
                            End Try
                        Else
                            Dim folders() As String = Split(newPath, "\")
                            Dim j As Integer
                            Dim catPath As String = ""
                            For j = 0 To folders.Count - 1
                                If j = 0 Then
                                    catPath = folders(j)
                                Else
                                    catPath = catPath & "\" & folders(j)
                                End If
                                Try
                                    asu.CreateDirectory(yourFileShare, Prefix & "\" & catPath)
                                Catch ex As Exception
    
                                End Try
                            Next
                        End If
    
                        newPath = Prefix & "/" & Replace(newPath, "\", "/")
    
                        Dim dt As Date = DateAndTime.Now
                        sw2.WriteLine("Attempting " & origPath & " at " & dt.ToLongTimeString & " on " & dt.ToShortDateString)
                        tsData1.Text = "#" & Trim(Str(i + 1)) & " of " & Trim(Str(txtFilesArray.Length))
    
                        Try
                            asu.UploadFileAsFileToAzureStorage(yourFileShare, newPath, origPath, asu.JobOnly(origPath) & Path.GetExtension(origPath))
                            sw2.WriteLine("Uploading ..." & origPath & "...success.")
                        Catch ex As Exception
                            sw2.WriteLine("Uploading ..." & origPath & "...failed.")
                        End Try
    
                        sw2.WriteLine(" ")
                    End If
                Next
    
                mWorking = False
            End While
    
            sw2.Close()
            sw2.Dispose()
            sw2 = Nothing
    
            WaitCursor(False)
    
            MsgBox("Done!")
        End Sub
    
        Public Sub WaitCursor(ByVal ShowHourglass As Boolean)
            If ShowHourglass = True Then
                Me.Cursor = Cursors.WaitCursor
            Else
                Me.Cursor = Cursors.Default
            End If
        End Sub
    
        Public Function GetAppPath() As String
            'Obtain the applications's path
            GetAppPath = System.IO.Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase.ToString())
    
            GetAppPath = Replace(GetAppPath, "file:\", "")
        End Function
    
        Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
            mWorking = False
        End Sub
    
        Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
        End Sub
    End Class
    

    第 6 步:运行项目

    假设您要克隆“D:\CRM”上的所有文件和子目录。为此,请在调试模式下运行项目 (F5)。那么,

    1. 单击“选择文件夹”按钮。您添加为 folderBrowserDialog 控件的 fbd1 现在将打开并允许您浏览要克隆的文件夹。在这种情况下,您将导航到“D:\CRM”文件夹并单击“确定”。 TextBox1 现在将显示您的文件夹选择 D:\CRM。
    2. 接下来,单击“上传到云端”按钮。该代码现在将枚举所选根文件夹中的所有文件和子目录。但是请注意,根目录中的任何实际文件都不会被枚举。
    3. 枚举完所有文件后,将弹出一个消息框。如果您碰巧有数千个文件和子目录,这可能需要一段时间。点击确定,开始文件/目录克隆!
    4. 代码中包含一个 StreamWriter,它将创建并写入日志文件,详细说明要传输的每个文件以及每个文件传输的结果(成功或失败)。日志文件位于应用的运行路径中,即应用的 bin\debug。
    5. 此外,在传输过程中,您会看到正在处理和上传的每个文件 #(即 512 个中的第 35 个)的更新。这要归功于添加的名为 tsData1 的 StatusStrip/ToolStripLabel。
    6. 如果您需要停止传输,请单击“取消”按钮。
    7. 请注意,如果由于某种原因需要重新开始,您可以使用 Azure 门户清除整个文件共享。请注意不要清除错误的文件共享!但这是“重新开始”的最简单方法,因为在使用门户时,除非文件夹为空,否则无法删除文件夹。
    8. Microsoft 提供了一个名为“Microsoft Azure Storage Explorer”的免费下载,这是一个非常适合处理您的 Azure 存储帐户的 PC 应用程序。
    9. 在表单代码的注释部分,我提到将“.png”更改为“.”以搜索所有文件。但是代码已经设置为使用“.”。但是,如果您只是在寻找特定的扩展名,那么请继续将“.”替换为“.[desired extension]”。然后,这将仅枚举那些文件,而不是所有文件。

    【讨论】:

      猜你喜欢
      • 2017-04-11
      • 2021-02-22
      • 2022-11-11
      • 1970-01-01
      • 2022-01-22
      • 2018-08-09
      • 1970-01-01
      • 2020-08-21
      • 2021-06-13
      相关资源
      最近更新 更多