none
How to avoid photo is replaced when they have same name

    Question

  • Hi Azure experts,

    I used code snippet below to download photo from blob, if there is one photo named photo.jpg in the path, it will replace photo.jpg, no matter it is same photo or not. How to get one copy of photo.jpg?

    // Retrieve storage account from connection string.
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
        CloudConfigurationManager.GetSetting("StorageConnectionString"));
    
    // Create the blob client.
    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
    
    // Retrieve reference to a previously created container.
    CloudBlobContainer container = blobClient.GetContainerReference("mycontainer");
    
    // Retrieve reference to a blob named "photo1.jpg".
    CloudBlockBlob blockBlob = container.GetBlockBlobReference("photo1.jpg");
    
    // Save blob contents to a file.
    using (var fileStream = System.IO.File.OpenWrite(@"path\photo.jpg"))
    {
        blockBlob.DownloadToStream(fileStream);
    }

    Thanks in advanced.

    Wednesday, June 1, 2016 9:18 AM

Answers

  • Before creating the filestream, you should check if photo.jpg already exists, and if it does use a different name.
    The following code can be used for this.
    var counter = 1;
    var path = @"path\photo.jpg";
    
    // Check if file exists
    while (File.Exists(path))
    {
        path = $@"path\photo({counter++}).jpg";
    }
    
    // Save blob contents to a file.
    using (var fileStream = System.IO.File.OpenWrite(path))
    {
        blockBlob.DownloadToStream(fileStream);
    }

    • Marked as answer by Juzer1 Thursday, June 2, 2016 1:08 PM
    Wednesday, June 1, 2016 10:46 AM

All replies

  • Before creating the filestream, you should check if photo.jpg already exists, and if it does use a different name.
    The following code can be used for this.
    var counter = 1;
    var path = @"path\photo.jpg";
    
    // Check if file exists
    while (File.Exists(path))
    {
        path = $@"path\photo({counter++}).jpg";
    }
    
    // Save blob contents to a file.
    using (var fileStream = System.IO.File.OpenWrite(path))
    {
        blockBlob.DownloadToStream(fileStream);
    }

    • Marked as answer by Juzer1 Thursday, June 2, 2016 1:08 PM
    Wednesday, June 1, 2016 10:46 AM
  • Thanks for suggestions, it's feasible to solve this problem.


    • Edited by Juzer1 Thursday, June 2, 2016 1:47 PM
    Thursday, June 2, 2016 1:08 PM