我必须在同一存储帐户的共享和blob之间移动一些文件。 经过一些谷歌搜索后,我最终得到了这段代码:
CloudFileClient fileClient = account.CreateCloudFileClient();
CloudFileShare share = fileClient.GetShareReference("shareName");
CloudFileDirectory rootDir = share.GetRootDirectoryReference();
CloudFileDirectory videoDirectory = rootDir.GetDirectoryReference(video.StoragePath);
CloudBlobClient blobClient = account.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference(video.StoragePath);
container.CreateIfNotExists();
foreach (var Files in videoDirectory.ListFilesAndDirectories())
{
var arr = Files.Uri.ToString().Split('/');
string strFileName = arr[arr.Length - 1];
CloudFile sourceFile = videoDirectory.GetFileReference(strFileName);
string fileSas = sourceFile.GetSharedAccessSignature(new SharedAccessFilePolicy()
{
Permissions = SharedAccessFilePermissions.Read,
SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24)
});
Uri fileSasUri = new Uri(sourceFile.StorageUri.PrimaryUri.ToString() + fileSas);
CloudBlockBlob blockBlob = container.GetBlockBlobReference(strFileName);
blockBlob.StartCopyAsync(fileSasUri).Wait(); //copy the file to blob storage and wait for the operation to complete
//sourceFile.DeleteAsync(); //delete the file
}
//videoDirectory.DeleteAsync(); //delete the directory
如果取消注释删除行,则目标包含源文件夹中的所有文件,但大小为0。
任何想法我做错了什么?
我还希望在复制所有文件后删除共享目录。有没有办法检查文件是否在目标文件夹中?
答案 0 :(得分:6)
据我所知,云blob StartCopyAsync方法意味着你告诉服务器端开始从文件存储中复制blob。
但它不会等待复制操作完全执行。
因此,如果要在文件完全执行后删除文件,则应使用FetchAttributes方法获取blob的状态。
如果状态已完成,您可以删除该文件。
更多细节,您可以参考以下代码:
CloudStorageAccount account = CloudStorageAccount.Parse(
"connection string");
CloudFileClient fileClient = account.CreateCloudFileClient();
CloudFileShare share = fileClient.GetShareReference("sharetest");
CloudFileDirectory rootDir = share.GetRootDirectoryReference();
CloudFileDirectory videoDirectory = rootDir.GetDirectoryReference("TestDirectory");
CloudBlobClient blobClient = account.CreateCloudBlobClient();
CloudBlobContainer container = blobClient.GetContainerReference("testdirectory");
container.CreateIfNotExists();
foreach (var Files in videoDirectory.ListFilesAndDirectories())
{
var arr = Files.Uri.ToString().Split('/');
string strFileName = arr[arr.Length - 1];
CloudFile sourceFile = videoDirectory.GetFileReference(strFileName);
string fileSas = sourceFile.GetSharedAccessSignature(new SharedAccessFilePolicy()
{
Permissions = SharedAccessFilePermissions.Read,
SharedAccessExpiryTime = DateTime.UtcNow.AddHours(24)
});
Uri fileSasUri = new Uri(sourceFile.StorageUri.PrimaryUri.ToString() + fileSas);
CloudBlockBlob blockBlob = container.GetBlockBlobReference(strFileName);
blockBlob.StartCopyAsync(fileSasUri).Wait();
blockBlob.FetchAttributes();
while (blockBlob.CopyState.Status == CopyStatus.Pending)
{
Thread.Sleep(50);
blockBlob.FetchAttributes();
}
if (blockBlob.CopyState.Status == CopyStatus.Success)
{
sourceFile.DeleteAsync();
}