如何将PC根目录中的所有文件和子目录上载到Azure存储帐户文件共享(文件而不是Blob)? 我的想法是,我想有效地“克隆” PC或硬盘上存在的所有文件和目录结构,并将其上传到我的Azure File Share。
答案 0 :(得分:0)
我需要将数千个文件及其文件夹上载到我的Azure存储帐户文件共享(文件,而不是Blob)。因此,我创建了一个简单的PC应用程序,可让我在PC(或连接的硬盘驱动器)上选择一个文件夹,单击一个按钮,瞧!然后,可以轻松地将文件和目录“克隆”到云中我的Azure File Share位置。
要开始,您需要在Visual Studio中创建一个新项目。我正在使用VS 2017。
第1步:创建一个新的Windows Forms应用
步骤2:我们需要添加一个名为WindowsAzure.Storage(v。9.3.3)的NuGet程序包,因此请转到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)上,放置以下控件:
第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)。然后,