为什么我从 Azure 存储下载的内容是空的?

Why is my download from Azure storage empty?

我可以连接到 Azure 存储帐户,甚至可以上传文件,但是当我使用 DownloadToFileAsync() 下载文件时,我得到了一个 0kb 的文件。

我检查过 "CloudFileDirectory" 和 "CloudFile" 字段都是正确的,这意味着与 Azure 的连接是可靠的。我什至可以将文件的输出写入控制台,但我似乎无法将其保存为文件。

public static string PullFromAzureStorage(string azureFileConn, string remoteFileName, string clientID)
        {
            var localDirectory = @"C:\cod\clients\" + clientID + @"\ftp\";
            var localFileName = clientID + "_xxx_" + remoteFileName;

            //Retrieve storage account from connection string
            var storageAccount = CloudStorageAccount.Parse(azureFileConn);
            var client = storageAccount.CreateCloudFileClient();
            var share = client.GetShareReference("testing");

            // Get a reference to the root directory for the share
            CloudFileDirectory rootDir = share.GetRootDirectoryReference();
            //Get a ref to client folder
            CloudFileDirectory cloudFileDirectory = rootDir.GetDirectoryReference(clientID);
            // Get a reference to the directory we created previously
            CloudFileDirectory unprocessed = cloudFileDirectory.GetDirectoryReference("Unprocessed");
            // Get a reference to the file
            CloudFile sourceFile = unprocessed.GetFileReference(remoteFileName);

            //write to console and log
            Console.WriteLine("Downloading file: " + remoteFileName);
            LogWriter.LogWrite("Downloading file: " + remoteFileName);

            //Console.WriteLine(sourceFile.DownloadTextAsync().Result);
            sourceFile.DownloadToFileAsync(Path.Combine(localDirectory, localFileName), FileMode.Create);

            //write to console and log
            Console.WriteLine("Download Successful!");
            LogWriter.LogWrite("Download Successful!");

            //delete remote file after download
            //sftp.DeleteFile(remoteDirectory + remoteFileName);

            return localFileName;    
        }

在将输出写入控制台的注释掉的代码行中,您明确使用了 .Result,因为您在同步方法中调用了 async 方法。您也应该在下载文件时也这样做,或者围绕它制作整个方法 async.

第一个解决方案如下所示:

sourceFile.DownloadToFileAsync(Path.Combine(localDirectory, localFileName), FileMode.Create).Result();

编辑:
至于使用 GetAwaiter().GetResult() 的注释的不同之处在于:.Result 包装了 AggregateException 中可能发生的任何异常,而 GetAwaiter().GetResult() 则不会。无论如何:如果有任何可能,您可以将方法重构为 async,以便您可以使用 await:请这样做。