Azure Blob AppendAllText

by ingvar 14. december 2010 10:04

There are a very limited way of reading/writing to a blob on Windows Azure. Basically you are stuck with OpenRead and OpenWrite which returns a read stream and a write stream respectively. So if you want to append some text to a file you have to do some coding your self. Here is an example of doing this in a read/write in same file version. Here I use a Exists method to determine if a blob exists or not. The implementation of the method can be found here.

CloudBlobContainer container; /* Initialize this */
CloudBlob blob = container.GetBlobReference("myblob.txt");
string contents; /* content to append */

if (blob.Exists())
{
    using (Stream blobStream = blob.OpenRead())
    {
        byte[] buffer = new byte[4096];
        using (Stream tempBlobStream = blob.OpenWrite())
        {
            int read;
            while ((read = blobStream.Read(buffer, 0, 4096)) > 0)
            {
                tempBlobStream.Write(buffer, 0, read);
            }

            using (StreamWriter writer = new StreamWriter(tempBlobStream))
            {
                writer.Write(contents);
            }
        }                       
    }
}
else
{
    using (Stream blobStream = blob.OpenRead())
    {
        using (StreamWriter writer = new StreamWriter(blobStream))
        {
            writer.Write(contents);
        }
    }
}

If you prefer you can do it in a in-memory version like this:

CloudBlobContainer container; /* Initialize this */
CloudBlob blob = container.GetBlobReference("myblob.txt");
string contents; /* content to append */

string oldContent;
if (!blob.Exists())
{
    oldContent = "";
}
else
{
    using (StreamReader reader = new StreamReader(blob.OpenRead()))
    {
        oldContent = reader.ReadToEnd();
    }
}

using (StreamWriter writer = new StreamWriter(blob.OpenWrite()))
{
    writer.Write(oldContent);
    writer.Write(contents);
}

Tags:

.NET | Azure | C# | Blob

About the author

Martin Ingvar Kofoed Jensen

Architect and Senior Developer at Composite on the open source project Composite C1 - C#/4.0, LINQ, Azure, Parallel and much more!

Follow me on Twitter

Read more about me here.

Read press and buzz about my work and me here.

Stack Overflow

Month List