1

I'm trying to download and save an .mp3 file from the internet, but got stuck with stream from the external link:

private void saveSound()
    {
        IsolatedStorageFile iso = IsolatedStorageFile.GetUserStoreForApplication();
        using (var fs = new IsolatedStorageFileStream("123.mp3", FileMode.Create, iso))
        {
            //Here should be this Stream from the Internet...
            //Uri: "http://my-site.com/mega-popular-song.mp3"
            StreamResourceInfo rs = new StreamResourceInfo(stream, "audio/mpeg");
            int count = 0;
            byte[] buffer = new byte[4096];
            while (0 < (count = rs.Stream.Read(buffer, 0, buffer.Length)))
            {
                fs.Write(buffer, 0, count);
            }
            fs.Close();

        }
    }

What should this stream look like? What is the best way to download and save .mp3 files?

Edward
  • 7,346
  • 8
  • 62
  • 123
Roman
  • 2,079
  • 4
  • 35
  • 53
  • 1
    I believe you need to get the stream from the args of a "webClient" Object and the Complete event Handler. – Bob Feb 15 '12 at 11:11

1 Answers1

1

I'm sure this article gets you there. Like Bob mentioned, you'll have to use a WebClient. Basically this is the code that does the magic:

wc.OpenReadCompleted += ((s, args) =>
{
    using (var store = IsolatedStorageFile.GetUserStoreForApplication())
    {
        if (store.FileExists(fileName))
            store.DeleteFile(fileName);

        using (var fs = new IsolatedStorageFileStream(fileName, FileMode.Create, store))
        {
            byte[] bytesInStream = new byte[args.Result.Length];
            args.Result.Read(bytesInStream, 0, (int)bytesInStream.Length);
            fs.Write(bytesInStream, 0, bytesInStream.Length);
            fs.Flush();
        }
    }
});

But I would read the complete article to fully understand what happens. Hope this helps!

Abbas
  • 14,186
  • 6
  • 41
  • 72