Dynamic System.IO.File.OpenRead

Hello:

I am trying to upload an images to Azure Blob Storage. The script below works fine. However, is there anyway to make these two lines dynamic based upon the user path and the uploaded file name

                    CloudBlockBlob blockBlob = container.GetBlockBlobReference("Test.jpg");
                    using (var fileStream = System.IO.File.OpenRead(@"C:\images\Test.jpg"))


            if (FileImgUpload.HasFile)
            {
                try
                {
                    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConn"));
                    CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
                    CloudBlobContainer container = blobClient.GetContainerReference("images");
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference("Test.jpg");
                    using (var fileStream = System.IO.File.OpenRead(@"C:\images\Test.jpg"))
                    {
                        blockBlob.UploadFromStream(fileStream);
                    } 
                    StatusText.Text = "Upload status: File uploaded!";
                }
                catch (Exception ex)
                {
                    StatusText.Text = "The following error: " + ex.Message;
                }
            }

Open in new window

LVL 1
RecipeDanAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

AndyAinscowFreelance programmer / ConsultantCommented:
String szImageName,  //="test.jpg"
String szImagePath;  //=@"C:\images\Test.jpg"
......
                    CloudBlockBlob blockBlob = container.GetBlockBlobReference(szImageName);
                    using (var fileStream = System.IO.File.OpenRead(szImagePath))

Just pass in the name and path you require
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
ste5anSenior DeveloperCommented:
Well, script? That's called programming. Just extract it to its own method:

Refactoring Extract Method
Now you have it in its own method as:

private static void UploadToAzure()
{
	CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConn"));
	CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
	CloudBlobContainer container = blobClient.GetContainerReference("images");
	CloudBlockBlob blockBlob = container.GetBlockBlobReference("Test.jpg");
	using (var fileStream = System.IO.File.OpenRead(@"C:\images\Test.jpg"))
	{
		blockBlob.UploadFromStream(fileStream);
	}
}

Open in new window


Now extract the literals to parameters:

private static void UploadToAzure(string localFileName)
{
	CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConn"));
	CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
	CloudBlobContainer container = blobClient.GetContainerReference("images");
	CloudBlockBlob blockBlob = container.GetBlockBlobReference(Path.GetFileName(localFileName));
	using (var fileStream = System.IO.File.OpenRead(localFileName))
	{
		blockBlob.UploadFromStream(fileStream);
	}
}

Open in new window


Now your code should look like:

if (FileImgUpload.HasFile)
{
	try
	{
		UploadToAzure(@"C:\images\Test.jpg");
		StatusText.Text = "Upload status: File uploaded!";
	}
	catch (Exception ex)
	{
		StatusText.Text = "The following error: " + ex.Message;
	}
}

Open in new window


As you are using FileUpload, it should look like this:

// Specify the path on the server to
// save the uploaded file to.
String savePath = @"c:\temp\uploads\";

// Before attempting to perform operations
// on the file, verify that the FileUpload 
// control contains a file.
if (FileUpload1.HasFile)
{
  // Get the name of the file to upload.
  String fileName = FileUpload1.FileName;

  // Append the name of the file to upload to the path.
  savePath += fileName;

  // Call the SaveAs method to save the 
  // uploaded file to the specified path.
  // This example does not perform all
  // the necessary error checking.               
  // If a file with the same name
  // already exists in the specified path,  
  // the uploaded file overwrites it.
  FileUpload1.SaveAs(savePath);

  // Move to Azure
  UploadToAzure(savePath);
  
  // Notify the user of the name of the file
  // was saved under.
  UploadStatusLabel.Text = "Your file was saved as " + fileName;
}
else
{      
  // Notify the user that a file was not uploaded.
  UploadStatusLabel.Text = "You did not specify a file to upload.";
}

Open in new window


p.s. @Andy: sz denotes a zero terminated string..
0
AndyAinscowFreelance programmer / ConsultantCommented:
>>p.s. @Andy: sz denotes a zero terminated string..

True, old (really, really old) habits die hard.
0
RecipeDanAuthor Commented:
I am getting an error message -  The following error: Could not find a part of the path 'C:\images\Test.jpg'.

It is there because when I clicked on browse that is the directory I got the file from.  Also how do you make these lines dynamic. C:Images is not always going to be the directory and Test.jpg is not always going to be the file name

      CloudBlockBlob blockBlob = container.GetBlockBlobReference("Test.jpg");
      using (var fileStream = System.IO.File.OpenRead(@"C:\images\Test.jpg"))
0
AndyAinscowFreelance programmer / ConsultantCommented:
Dynamic - please read my comment and implement that, that is precisely what I addressed.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
C#

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.