views:

33

answers:

1

I want my Azure application to create a blob and write a data into it. When I tried it I got this exception stating that

ArgumentException was unhandled

Stream was not writable

here is my code

var ms = new MemoryStream();
            for (int k = 0; k < 10; k++)
            {
                using (StreamWriter sw = new StreamWriter(ms))
                {
                    string val = k.ToString();
                    if (k + 1 != len)
                        val = val + " ";
                    sw.Write(val);
                    sw.Flush();
                }
            }
            ms.Position = 0;
            blob.UploadFromStream(ms);

My code is getting executed for k = 0. The exception is thrown when k = 1. Can anyone tell me how to solve this exception

Moreover, Is this the correct procedure for writing onto the blob. If no, where am I went wrong and how to correct it.

+1  A: 

My guess is that the Finalize method of StreamWriter closes the underlying stream (so next time through the loop, you can't write to that MemoryStream).

I think you can solve this by puting the "using (StreamWriter sw = new StreamWriter(ms))" block around the whole loop. It's presumably more efficient than creating a new StreamWriter each time anyway.

In any case, if you're just writing text, it might be better to do something like:

StringBuilder sb = new StringBuilder();
for (int k = 0; k < 10; k++)
{
    sb.Append(k.ToString());
    if (k + 1 != len) sb.Append(" ");
}
blob.UploadText(sb.ToString());

Or (for this particular use), get fancy. :-) (completely untested):

blob.UploadText(string.Join(" ", Enumerable.Range(0, 10).Select(k => k.ToString()).ToArray()));
smarx