C# 为什么我从Azure存储下载的内容是空的?
我可以连接到Azure存储帐户,甚至可以上载文件,但当我使用DownloadToFileAsync()下载文件时,结果会得到一个0 KB的文件 我已经检查过了,“CloudFileDirectory”和“CloudFile”字段都是正确的,这意味着与Azure的连接是可靠的。我甚至可以将文件的输出写入控制台,但似乎无法将其保存为文件C# 为什么我从Azure存储下载的内容是空的?,c#,download,azure-storage,azure-files,C#,Download,Azure Storage,Azure Files,我可以连接到Azure存储帐户,甚至可以上载文件,但当我使用DownloadToFileAsync()下载文件时,结果会得到一个0 KB的文件 我已经检查过了,“CloudFileDirectory”和“CloudFile”字段都是正确的,这意味着与Azure的连接是可靠的。我甚至可以将文件的输出写入控制台,但似乎无法将其保存为文件 public static string PullFromAzureStorage(string azureFileConn, string remoteFileN
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
包装了聚合异常中可能发生的任何异常,而GetAwaiter().GetResult()
不会。无论如何:如果有任何可能,您可以将该方法重构为async
,这样您就可以使用wait
:请这样做 sourceFile.DownloadToFileAsync(Path.Combine(localDirectory,localFileName),FileMode.Create.GetAwaiter().GetResult()代码>谢谢!这个解决方案肯定有效。正在努力使该方法异步,以便尽可能使用原始语句。当我等待该语句并使该方法异步(也是我首选的方法)时,我得到了响应System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.String,ComplianceOnDemand.FileHandler+d_u3]
,当我尝试在该语句上使用.Result时,我得到的“Task”不包含“Result”的定义,并且找不到接受“Task”类型的第一个参数的可访问扩展方法“Result”(是否缺少using指令或程序集引用?