Windows Azure Blob(3) - How to read file from blob

        static void CopyStream(Stream sourceStream, Stream destinationStream)
        {
            const int BufferSize = 0x10000;
            byte[] buffer = new byte[BufferSize];
            int n = 0;
            do
            {
                n = sourceStream.Read(buffer, 0, BufferSize);
                if (n > 0)
                {
                    destinationStream.Write(buffer, 0, n);
                }

            } while (n > 0);
        }


        static void Main(string[] args)
        {
            Uri uri = new Uri("http://127.0.0.1:10000/devstoreaccount1/storagesamplecontainer/hello.txt?timeout=30");
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(uri);
            request.Timeout = 30000;
            request.ReadWriteTimeout = 30000;
            request.Method = "GET";
            request.ContentLength = 0;
            request.Headers.Add("x-ms-date", DateTime.UtcNow.ToString("R", CultureInfo.InvariantCulture));
            request.Headers.Add("x-ms-meta-Name", "StorageSample");

            string accountName = "devstoreaccount1";
            string base64Key = "Eby8vdM02xNOcqFlqUwJPLlmEtlCDXJ1OUzFT50uSRZ6IFsuFq2UVErCz4I6tq/K1SZFPTOtr/KBHBeksoGMGw==";
            byte[] key = Convert.FromBase64String(base64Key);
            ResourceUriComponents uriComponents = new ResourceUriComponents("devstoreaccount1", "storagesamplecontainer", null);

            SharedKeyCredentials credentials = new SharedKeyCredentials(accountName, key);
            credentials.SignRequest(request, uriComponents);

            Stream stream = new MemoryStream();
            try
            {
                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    if (response.StatusCode == HttpStatusCode.OK
                        || response.StatusCode == HttpStatusCode.PartialContent)
                    {
                        using (Stream responseStream = response.GetResponseStream())
                        {
                            CopyStream(responseStream, stream);
                        }
                    }
                    else
                    {
                        Console.WriteLine("error");
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            stream.Seek(0, SeekOrigin.Begin);
            byte[] bytes = new byte[stream.Length];
            int n = 0;
            int offset = 0;
            do
            {
                n = stream.Read(bytes, offset, bytes.Length - offset);
                offset += n;

            } while (n > 0);

            string value = Encoding.UTF8.GetString(bytes);

            Console.WriteLine(value);

        }

posted on 2009-01-19 23:08  Yang - Windows Azure  阅读(328)  评论(0编辑  收藏  举报

导航