I am using "Azure Storage File Shares" to store some files from our website, but failed with error message "The specified share already exists".
I have change the file that being upload, but the error persist.
Here my code
public static void Test2Upload()
{
System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;
string connectionString = "DefaultEndpointsProtocol=https;AccountName=xxxxx;AccountKey=xxxxx;EndpointSuffix=core.windows.net";
string shareName = "myapp-dev";
string dirName = "files";
string fileName = "catto.jpg";
// Path to the local file to upload
string localFilePath = @"d:temptwo.jpg";
// Get a reference to a share and then create it
ShareClient share = new ShareClient(connectionString, shareName);
share.Create();
// Get a reference to a directory and create it
ShareDirectoryClient directory = share.GetDirectoryClient(dirName);
directory.Create();
// Get a reference to a file and upload it
ShareFileClient file = directory.GetFileClient(fileName);
using (FileStream stream = File.OpenRead(localFilePath))
{
file.Create(stream.Length);
file.UploadRange(
new HttpRange(0, stream.Length),
stream);
}
}
Looks like I should not create ShareClient with same name several times.
Then how to check and use it?
The most important question is, why the file still not yet uploaded (even if I rename the ShareClient object)?
2
Answers
We could use ShareClient.CreateIfNotExists when creating ShareClient object to avoid the problem. Like below
You might found Similar problem on ShareDirectoryClient. This part purpose is to create the folder structure. The upload will fail if the destination folder is not exist.
Error will occur if we create a folder when it already exist. So, use method ShareDirectoryClient.CreateIfNotExists, like below
Here my complete code
You can use
ShareClient.CreateIfNotExists
instead ofShareClient.Create
method. Former will try to create a share but if a share already exists, then it won’t be changed.You can also use
ShareClient.Exists
to check if the share exists and then create it usingShareClient.Create
if it does not exist. This is not recommended however as it might not work if multiple users are executing that code at the same time. Furthermore, you will be making 2 network calls – first to check the existence of share and then the second to create it.Your code for uploading the file looks ok to me. Are you getting any error in that code?