从HTTP获取资源并保存到Iso Storage

时间:2011-10-23 18:42:44

标签: c# silverlight windows-phone-7 isolatedstorage

我目前正在使用此代码将medai保存到隔离存储。如果媒体是本地媒体,这可以工作,但当我尝试从http地址获得medai时,我在URiKind上收到错误。我已经从绝对改变了。相对,但仍然没有骰子。

有什么建议吗?

FYI - filename = http://www.domain.com/media.wma

错误:无法创建相对URI,因为'uriString'参数表示绝对URI。

或者:预期的相对Uri,被发现是绝对的。

private void DownloadToIsoStore(string fileName)
        {

            string ringtonePath = GetRingtonePath();

            IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();

            // If the file already exists, no need to "download", just return
            if (isoStore.FileExists(fileName))
            {
                return;
            }

            StreamResourceInfo sr = Application.GetResourceStream(new Uri(fileName, UriKind.Relative));

            using (BinaryReader br = new BinaryReader(sr.Stream))
            {
                // Simulate "downloading" medai file
                byte[] data = br.ReadBytes((int)sr.Stream.Length);

                // Save to local isolated storage
                SaveToIsoStore(fileName, data);
            }

        }

2 个答案:

答案 0 :(得分:1)

Application.GetResourceStream获取应用程序中嵌入的资源的相对URI 它不是HTTP客户端。

相反,您应该使用WebClientHttpWebRequest类。

答案 1 :(得分:1)

您可以使用以下代码 1.使用参数(http://www.domain.com/media.wma)

调用此函数
    public void **GetMediaFile**(string httpPath)
    {
        WebClient wcMedia = new WebClient();
        wcMedia.OpenReadAsync(new Uri(httpPath));
        wcMedia.OpenReadCompleted += new OpenReadCompletedEventHandler(wcMedia_OpenReadCompleted);
        wcMedia.AllowReadStreamBuffering = true;

    }

2.Event Handler将媒体文件下载到隔离存储内的所需(iso_path)位置。

    void wcMedia_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
    {       
        string iso_path="path where you want to put media file insode the isolated storage";
        var isolatedfile = IsolatedStorageFile.GetUserStoreForApplication();
        using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(iso_path, System.IO.FileMode.Create, isolatedfile))
        {
            byte[] buffer = new byte[e.Result.Length];
            while (e.Result.Read(buffer, 0, buffer.Length) > 0)
            {
                stream.Write(buffer, 0, buffer.Length);
            }
        }

}