Exportera (0) Skriv ut
Visa allt
EN
Det här innehållet finns inte tillgängligt på ditt språk men här finns den engelska versionen,

Conditionally Refresh a Local Copy of a Blob

Updated: February 20, 2013

A blob can be downloaded conditionally by including a condition in the AccessCondition property. The following code example sets the date and time of the last refresh in the IfModifiedSince method. The Blob service compares this value to the time the blob was last modified. If the blob has not been modified since the specified time, the DownloadToFile method throws a StorageClientException with the StatusCode property set to System.Net.HttpStatusCode.NotModified. Note that the Blob service times are in Coordinated Universal Time (UTC).

class RefreshLocalCopy
{
    const string MY_FILE = @"c:\temp\myfile.txt";
    static DateTime revTimeOfLastDownloaded = new DateTime(1900, 1, 1); // old

    static void Main(string[] args)
    {
        CloudBlobClient blobClient = new CloudBlobClient(
            "https://myaccount.blob.core.windows.net/",
            new StorageCredentialsAccountAndKey("myaccount", "mykey=="));

        string s = "testcontainer/" + System.IO.Path.GetFileName(MY_FILE);
        CloudBlob blob = blobClient.GetBlobReference(s);

        ReadBlobIfUpdated( blob );  // downloads the blob
        blob.UploadFile( MY_FILE ); // updates the blob
        ReadBlobIfUpdated( blob );  // downloads the updated blob
        ReadBlobIfUpdated(blob);    // notices no changes
    }

    static void ReadBlobIfUpdated(CloudBlob blob)
    {
        try
        {
            blob.FetchAttributes();

            blob.DownloadToFile(MY_FILE,
                new BlobRequestOptions() 
                    { AccessCondition =
                        AccessCondition.IfModifiedSince(revTimeOfLastDownloaded) }
            );

            // code reached when download succeeds (w/ no exception)
            revTimeOfLastDownloaded = blob.Attributes.Properties.LastModifiedUtc; 
        }
        catch (StorageClientException e)
        {
            if (e.StatusCode == System.Net.HttpStatusCode.NotModified)
            {
                Console.WriteLine("Blob not modified since our last read.");
                return;
            }

            throw e; // some other storage exception? rethrow
        }
    }
}

See Also

Concepts

Storage

Visa:
© 2014 Microsoft