46

How can I to Upload a file with C# ? I need to upload a file from a dialogWindow.

3
  • Check out Blob transfer utility its a great project, all in c#. It'll show you how. Commented Sep 3, 2013 at 16:44
  • Here's a C# wrapper on GitHub, it works with Azure blobs or Amazon S3, and supports local caching and version checking. Commented Sep 6, 2015 at 2:52
  • This C# Azure Blob Storage Manager class is pretty good basic class file if anyone's in need of a class for their C# projects. Commented Jul 3, 2016 at 8:47

6 Answers 6

68
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Auth;
using Microsoft.WindowsAzure.Storage.Blob;    

// Retrieve storage account from connection string.
    CloudStorageAccount storageAccount = CloudStorageAccount.Parse("StorageKey");

// 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 "myblob".
CloudBlockBlob blockBlob = container.GetBlockBlobReference("myblob");

// Create or overwrite the "myblob" blob with contents from a local file.
using (var fileStream = System.IO.File.OpenRead(@"path\myfile"))
{
    blockBlob.UploadFromStream(fileStream);
}

see here about needed SDK and references

i think it's what you need

Sign up to request clarification or add additional context in comments.

3 Comments

This still works 2018. Just replace blockBlob.UploadFromStream(fileStream); with await blockBlob.UploadFromStreamAsync(fileStream);
For newbies like me: "myblob" is just the destination file name.
These libraries are all legacy now. Don't use this code
12

Since WindowsAzure.Storage is legacy. With Microsoft.Azure.Storage.* we can use the following code to upload

  static async Task CreateBlob()
    {
        
        BlobServiceClient blobServiceClient = new BlobServiceClient(storageconnstring);
        
        BlobContainerClient containerClient = blobServiceClient.GetBlobContainerClient(containerName);
        
        BlobClient blobClient = containerClient.GetBlobClient(filename);

        
        using FileStream uploadFileStream = File.OpenRead(filepath);
        
        await blobClient.UploadAsync(uploadFileStream, true);
        uploadFileStream.Close();
    }

Comments

3

The following code snippet is the simplest form of performing the file uploading. I have added a few more lines to this code, in order to detect the uploading file type and check the container exeistance.

Note:- you need to add the following NuGet packages first.

  1. Microsoft.AspNetCore.StaticFiles

  2. Microsoft.Azure.Storage.Blob

  3. Microsoft.Extensions.Configuration

    static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        string connstring = "DefaultEndpointsProtocol=https;AccountName=storageaccountnewne9d7b;AccountKey=3sUU8J5pQQ+6YYIi+b5jo+BiSb5XPt027Rve6N5QP9iPEhMXZAbzUfsuW7QDWi1gSPecsPFpC6AzmA9jwPYs6g==;EndpointSuffix=core.windows.net";
        string containername = "newturorial";
        string finlename = "TestUpload.docx";
        var fileBytes = System.IO.File.ReadAllBytes(@"C:\Users\Namal Wijekoon\Desktop\HardningSprint2LoadTest\" + finlename);
    
        var cloudstorageAccount = CloudStorageAccount.Parse(connstring);
        var cloudblobClient = cloudstorageAccount.CreateCloudBlobClient();
        var containerObject = cloudblobClient.GetContainerReference(containername);
    
        //check the container existance
        if (containerObject.CreateIfNotExistsAsync().Result)
        {
            containerObject.SetPermissionsAsync(new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob });
        }
        var fileobject = containerObject.GetBlockBlobReference(finlename);
    
        //check the file type
        string file_type;
        var provider = new FileExtensionContentTypeProvider();
        if(!provider.TryGetContentType(finlename, out file_type))
        {
            file_type = "application/octet-stream";
        }
    
        fileobject.Properties.ContentType = file_type;
        fileobject.UploadFromByteArrayAsync(fileBytes, 0 , fileBytes.Length);
    
        string fileuploadURI = fileobject.Uri.AbsoluteUri;
        Console.WriteLine("File has be uploaded successfully.");
        Console.WriteLine("The URL of the Uploaded file is : - \n" + fileuploadURI);
    }
    

1 Comment

CloudStorageAccount is found in Microsoft.WindowsAzure.Storage, not Microsoft.Azure.Storage.
2

we can use BackgroundUploader class ,Then we need to provide StorageFile object and a Uri: Required Namespaces:

using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Networking.BackgroundTransfer;
using Windows.Storage.Pickers;
using Windows.Storage;

The process is Like This : Uri is defined using a string value provided via a UI input field, and the desired file for upload, represented by a StorageFile object, is returned when the end-user has selected a file through the UI provided by the PickSingleFileAsync operation

Uri uri = new Uri(serverAddressField.Text.Trim());
FileOpenPicker picker = new FileOpenPicker();
picker.FileTypeFilter.Add("*");
StorageFile file = await picker.PickSingleFileAsync();

and Then:

BackgroundUploader uploader = new BackgroundUploader();
uploader.SetRequestHeader("Filename", file.Name);
UploadOperation upload = uploader.CreateUpload(uri, file);

// Attach progress and completion handlers.
await HandleUploadAsync(upload, true);

Thats All

Comments

2

Here is the complete method.

 [HttpPost]
        public ActionResult Index(Doctor doct, HttpPostedFileBase photo)
        {

            try
            {
                if (photo != null && photo.ContentLength > 0)
                {
                    // extract only the fielname
                    var fileName = Path.GetFileName(photo.FileName);
                    doct.Image = fileName.ToString();

                    CloudStorageAccount cloudStorageAccount = DoctorController.GetConnectionString();
                    CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
                    CloudBlobContainer cloudBlobContainer = cloudBlobClient.GetContainerReference("images");


                    string imageName = Guid.NewGuid().ToString() + "-" +Path.GetExtension(photo.FileName); 

                    CloudBlockBlob BlockBlob = cloudBlobContainer.GetBlockBlobReference(imageName);

                    BlockBlob.Properties.ContentType = photo.ContentType;
                    BlockBlob.UploadFromStreamAsync(photo.InputStream);
                    string imageFullPath = BlockBlob.Uri.ToString();

                    var memoryStream = new MemoryStream();


                    photo.InputStream.CopyTo(memoryStream);
                    memoryStream.ToArray();



                    memoryStream.Seek(0, SeekOrigin.Begin);
                    using (var fs = photo.InputStream)
                    {
                        BlockBlob.UploadFromStreamAsync(memoryStream);
                    }

                }
            }
            catch (Exception ex)
            {

            }


            return View();
        }

where the getconnectionstring method is this.

 static string accountname = ConfigurationManager.AppSettings["accountName"];
      static  string key = ConfigurationManager.AppSettings["key"];


            public static CloudStorageAccount GetConnectionString()
            {

                string connectionString = string.Format("DefaultEndpointsProtocol=https;AccountName={0};AccountKey={1}", accountname, key);
                return CloudStorageAccount.Parse(connectionString);
            }

1 Comment

It seems that this would upload the stream twice, no?
1

Complete Web API Controller to upload single or multiple files. .NET Framework 4.8

Install NuGet package, Azure.Storage.Blob

using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Blob;
using System;
using System.Configuration;
using System.Web;
using System.Web.Http;

namespace api.azure.Controllers
{
    public class FileController : ApiController
    {
        [HttpPost]
        [Route("api/BlobStorage/UploadFiles")]
        public IHttpActionResult UploadFiles()
        {
            string result = "";
            try
            {
                result = UploadFilesToBlob();
            }
            catch (Exception ex)
            {
                return Ok(ex.Message);
            }

            return Ok(result);
        }

        public string UploadFilesToBlob()
        {
            try
            {
                string storageConnectionString = ConfigurationManager.AppSettings["BlobStorageConnectionString"];
                CloudStorageAccount blobStorage = CloudStorageAccount.Parse(storageConnectionString);
                CloudBlobClient blobClient = blobStorage.CreateCloudBlobClient();
                if (HttpContext.Current.Request.Form["BlobContainerName"] != null)
                {
                    string blobContainerName = HttpContext.Current.Request.Form["BlobContainerName"].ToString();
                    CloudBlobContainer container = blobClient.GetContainerReference(blobContainerName);
                    container.CreateIfNotExists();

                    // Set public access level to the container.
                    container.SetPermissions(new BlobContainerPermissions()
                    {
                        PublicAccess = BlobContainerPublicAccessType.Container
                    });

                    string folderName = "";
                    if (HttpContext.Current.Request.Form["FolderNameToUploadFiles"] != null)
                    folderName = HttpContext.Current.Request.Form["FolderNameToUploadFiles"].ToString() + "/";

                    for (int i = 0; i < HttpContext.Current.Request.Files.Count; i++)
                    {
                        var httpPostedFile = HttpContext.Current.Request.Files[i];
                        if (httpPostedFile != null)
                        {
                            string blobName = folderName + httpPostedFile.FileName;
                            CloudBlockBlob blob = container.GetBlockBlobReference(blobName);
                            blob.UploadFromStream(httpPostedFile.InputStream);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return "# of file(s) sent to upload: " + HttpContext.Current.Request.Files.Count.ToString();

        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.