Darth Veder
Darth Veder

Reputation: 159

Downloading file from url and saving to blob

I have an azure function that downloads a file to a temporary file path and then saves the temp file to a blob. I have two questions:

1) Is there a way to manage the temporary files created by the function Path.GetTempFileName(). i.e after the scope of the function delete the temp filename?

2) Is there a better practice for downloading files from a url to a blob?

var filename = Path.GetTempFileName();
WebClient myWebClient = new WebClient();
myWebClient.DownloadFile(url, filename);
using (var fileStream = System.IO.File.OpenRead(filename))
{
    blob.UploadFromStream(fileStream);
}

Upvotes: 2

Views: 4010

Answers (2)

Zhaoxing Lu
Zhaoxing Lu

Reputation: 6467

Actually you can directly perform server side copy from source URL via CloudBlob.StartCopy instead of downloading and then downloading:

var account = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
var blobClient = account.CreateCloudBlobClient();
var blobContainer = blobClient.GetContainerReference(destinationContainer);
blobContainer.CreateIfNotExists();
var newBlockBlob = blobContainer.GetBlockBlobReference(newFileName);
newBlockBlob.StartCopy(new Uri(sourceUrl));

// Monitor the copy state
while (true)
{
    newBlockBlob.FetchAttributes();
    Console.WriteLine("Copy state: {0}", newBlockBlob.CopyState);
    if (newBlockBlob.CopyState.Status != CopyStatus.Pending)
    {
        break;
    }

    Thread.Sleep(waitTime);
}

Upvotes: 0

Chris Gillum
Chris Gillum

Reputation: 15052

Rather than downloading to the local file system, a more efficient approach would be to stream the URL contents directly to the blob stream. Something like this:

HttpWebRequest request = HttpWebRequest.CreateHttp(url);
using (WebResponse response = await request.GetResponseAsync())
using (Stream dataStream = response.GetResponseStream())
{
    await blob.UploadFromStreamAsync(dataStream);
}

Upvotes: 2

Related Questions