I have the following routine that downloads a file from a web server. Sometimes the local file is created, but is zero bytes. I am [almost] certain the remote resource exists.
private static void DownloadFile(string strUrl, string strLocalFile)
{
using (var client = new HttpClient())
{
using (var httpClient = new HttpClient())
{
using (var streamAsync = httpClient.GetStreamAsync(strUrl))
{
using (var fileStream = new FileStream(strLocalFile, FileMode.OpenOrCreate))
{
streamAsync.Result.CopyTo(fileStream);
}
}
}
}
}
...Asyncwithoutawaitis the issue.HttpClients ?await, you can generally handleTask.WhenAll,Task.WhenAny, orTask.ContinueWith, and check the result in the handler.Resultblocks until theTask<>is complete. This isn't the recommended way to consume an async API, but it should work.