Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Dynamic System.IO.File.OpenRead

Posted on 2014-08-23
5
Medium Priority
?
593 Views
Last Modified: 2014-11-12
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

0
Comment
Question by:RecipeDan
  • 3
5 Comments
 
LVL 45

Accepted Solution

by:
AndyAinscow earned 1000 total points
ID: 40280248
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
 
LVL 36

Assisted Solution

by:ste5an
ste5an earned 1000 total points
ID: 40280400
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
 
LVL 45

Expert Comment

by:AndyAinscow
ID: 40280417
>>p.s. @Andy: sz denotes a zero terminated string..

True, old (really, really old) habits die hard.
0
 
LVL 1

Author Comment

by:RecipeDan
ID: 40280529
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
 
LVL 45

Expert Comment

by:AndyAinscow
ID: 40280567
Dynamic - please read my comment and implement that, that is precisely what I addressed.
0

Featured Post

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Windocks is an independent port of Docker's open source to Windows.   This article introduces the use of SQL Server in containers, with integrated support of SQL Server database cloning.
High user turnover can cause old/redundant user data to consume valuable space. UserResourceCleanup was developed to address this by automatically deleting user folders when the user account is deleted.
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, just open a new email message. In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…
Suggested Courses

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question