Code Monkey home page Code Monkey logo

storage-blob-dotnet-store-temp-files's Introduction

services platforms author
blobs
c#
msonecode

Store temp files by Azure Blob storage on Azure applications

This sample demonstrates how to store temp files by Azure Blob storage in Azure applications

Introduction

This sample demonstrates how to store temp file in Azure applications.

We have two solutions:

  1. First one is the traditional way of calling ‘Path.GetTempPath()’ to store temp file in all windows platform.
  2. The other one is specific for Azure by using blob object in Azure to simulate temp file.

Building the Sample

  1. Double click CSAzureTempFiles.sln file to open this sample solution by using Microsoft Visual Studio 2012 or the later version(s).
  2. Restore nugget packages in the solution restore-nuget-package
  3. Copy account name, access key and address of your azure storage account. get-access-keys get-container-url
  4. Configure necessary parameters about account name, key and address in the solution in file Controllers\AzureBlobController.cs config-AzureBlobController

Running the Sample

You can upload the sample to your Azure storage, or run at your local IIS, or just debug it in your Visual Studio.

Using the Code

Solution1:

private void SaveTempFile(HttpPostedFileBase file)
{
    //get the uploaded file name
    string fileName = file.FileName;

    //get temp directory path
    string tempPath = Path.GetTempPath();

    //init the file path
    string filePath = tempPath + fileName;

    //if the path is exists,delete old file
    if (System.IO.File.Exists(filePath))
    {
        System.IO.File.Delete(filePath);
    }

    //and then save new file
    file.SaveAs(filePath);
}

Solution 2:

private async Task SaveTempFile(string fileName, long contentLenght, Stream inputStream)
{
    try
    {
        //firstly, we need check the container if exists or not. And if not, we need to create one.
        await container.CreateIfNotExistsAsync();

        //init a blobReference
        CloudBlockBlob tempFileBlob = container.GetBlockBlobReference(fileName);

        //if the blobReference is exists, delete the old blob
        tempFileBlob.DeleteIfExists();

        //check the count of blob if over limit or not, if yes, clear them.
        await CleanStorageIfReachLimit(contentLenght);

        //and upload the new file in this
        tempFileBlob.UploadFromStream(inputStream);
    }
    catch (Exception ex)
    {
        if (ex.InnerException != null)
        {
            throw ex.InnerException;
        }
        else
        {
            throw ex;
        }
    }
}

//check the count of blob if over limit or not, if yes, clear them. 
private async Task CleanStorageIfReachLimit(long newFileLength)
{
    List<CloudBlob> blobs = container.ListBlobs()
        .OfType<CloudBlob>()
        .OrderBy(m => m.Properties.LastModified)
        .ToList();

    //get total size of all blobs.
    long totalSize = blobs.Sum(m => m.Properties.Length);

    //calculate out the real limit size of before upload
    long realLimetSize = TotalLimitSizeOfTempFiles - newFileLength;

    //delete all,when the free size is enough, break this loop,and stop delete blob anymore
    foreach (CloudBlob item in blobs)
    {
        if (totalSize <= realLimetSize)
        {
            break;
        }

        await item.DeleteIfExistsAsync();
        totalSize -= item.Properties.Length;
    }
} 

More Information and Resources

storage-blob-dotnet-store-temp-files's People

Contributors

acomsmpbot avatar aliceqin12 avatar msonecode avatar silentdance avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.