3
votes

I am trying to rename blob in azure storage via .net API and it is I am unable to rename a blob file after a day : (

Here is how I am doing it, by creating new blob and copy from old one.

var newBlob = blobContainer.GetBlobReferenceFromServer(filename);

newBlob.StartCopyFromBlob(blob.Uri);

blob.Delete();

There is no new blob on server so I am getting http 404 Not Found exception.

Here is working example that i have found but it is for old .net Storage api.

CloudBlob blob = container.GetBlobReference(sourceBlobName);
CloudBlob newBlob = container.GetBlobReference(destBlobName);
newBlob.UploadByteArray(new byte[] { });
newBlob.CopyFromBlob(blob);
blob.Delete();

Currently I am using 2.0 API. Where I am I making a mistake?

2

2 Answers

7
votes

I see that you're using GetBlobReferenceFromServer method to create an instance of new blob object. For this function to work, the blob must be present which will not be the case as you're trying to rename the blob.

What you could do is call GetBlobReferenceFromServer on the old blob, get it's type and then either create an instance of BlockBlob or PageBlob and perform copy operation on that. So your code would be something like:

    CloudBlobContainer blobContainer = storageAccount.CreateCloudBlobClient().GetContainerReference("container");
    var blob = blobContainer.GetBlobReferenceFromServer("oldblobname");
    ICloudBlob newBlob = null;
    if (blob is CloudBlockBlob)
    {
        newBlob = blobContainer.GetBlockBlobReference("newblobname");
    }
    else
    {
        newBlob = blobContainer.GetPageBlobReference("newblobname");
    }
    //Initiate blob copy
    newBlob.StartCopyFromBlob(blob.Uri);
    //Now wait in the loop for the copy operation to finish
    while (true)
    {
        newBlob.FetchAttributes();
        if (newBlob.CopyState.Status != CopyStatus.Pending)
        {
            break;
        }
        //Sleep for a second may be
        System.Threading.Thread.Sleep(1000);
    }
    blob.Delete();
0
votes

The code in OP was almost fine except that an async copy method was called. The simplest code in new API should be:

var oldBlob = cloudBlobClient.GetBlobReferenceFromServer(oldBlobUri);
var newBlob = container.GetBlobReference("newblobname");
newBlog.CopyFromBlob(oldBlob);
oldBlob.Delete();