【问题标题】:Downloading files and opening them下载文件并打开它们
【发布时间】:2013-12-16 16:36:06
【问题描述】:

我有一个应该显示视频文件的用户控件。

代码是:

//The code does: Checks if file exists, if yes - opens, if not - goes to download manager and downloads it. 
//After await dMan.downloadVideo(link); finishes - function recursivly calls itself, but code runs into Unauthorized Access Exception
private async void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        await LoadVideo();
    }

    private async Task LoadVideo()
    {
        string link = "http://samples.mplayerhq.hu/MPEG-4/MargotGagnon.mov";
        DownloadManager dMan = new DownloadManager();
        bool FileNeedsDownload = false;
        try
        {
            Windows.Storage.StorageFile sampleFile = await ApplicationData.Current.LocalFolder.GetFileAsync("Margot.mp4");
            var stream = await sampleFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
            VideoPlayer.SetSource(stream, sampleFile.FileType);
        }
        catch
        {
            FileNeedsDownload = true;
        }
        if (FileNeedsDownload == true)
        {
            await dMan.downloadVideo(link);
            LoadVideo();
        }
    }

我的下载代码:

public async Task downloadVideo(string link)
    {
        string path = ApplicationData.Current.LocalFolder.Path.ToString();
            string urlLink = link;
            await getVideoByUrl(urlLink, "Margot.mp4");
    }
    async public Task getVideoByUrl(string url, string filename)
    {
        HttpClientHandler aHandler = new HttpClientHandler();
        aHandler.ClientCertificateOptions = ClientCertificateOption.Automatic;
        HttpClient aClient = new HttpClient(aHandler);
        aClient.DefaultRequestHeaders.ExpectContinue = false;
        HttpResponseMessage response = await aClient.GetAsync(url);
        byte[] img = await response.Content.ReadAsByteArrayAsync();// ReadAsByteArray();
        InMemoryRandomAccessStream randomAccessStream = new InMemoryRandomAccessStream();

        // To save downloaded image to local storage
        var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
        filename, CreationCollisionOption.ReplaceExisting);
        var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);
        DataWriter writer = new DataWriter(fs.GetOutputStreamAt(0));

        writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
        await writer.StoreAsync();
        //current.image.SetSource(randomAccessStream);
        writer.DetachStream();
        await fs.FlushAsync();

        // To save downloaded image to bitmap
        //DataWriter writer2 = new DataWriter(randomAccessStream.GetOutputStreamAt(0));
        //writer2.WriteBytes(img);
        //await writer2.StoreAsync();
        //current.image = new BitmapImage();
        //current.image.SetSource(randomAccessStream);
    }

例外:

System.UnauthorizedAccessException 被捕获 H结果=-2147024891 消息=访问被拒绝。 (来自 HRESULT 的异常:0x80070005 (E_ACCESSDENIED)) 源=mscorlib 堆栈跟踪: 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务任务) 在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务任务) 在 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() 在 c:\Users\afomenko\Desktop***\Controls\VideoControl.xaml.cs:line 43 中的 SalesPlays.Controls.VideoControl.d__3.MoveNext() 内部异常:

附注当我在暗恋后运行应用程序时 - 视频被下载(当然,因为下载有效)并打开视频。为什么它在第一次未授权时失败?

也许我的下载器中没有关闭某些流?

【问题讨论】:

    标签: c# file windows-8 download windows-8.1


    【解决方案1】:

    解决方案在我的保存代码中!

    这是一个工作示例:

    var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, Windows.Storage.CreationCollisionOption.ReplaceExisting);
    using (var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
    {
        var outStream = fs.GetOutputStreamAt(0);
        var dataWriter = new Windows.Storage.Streams.DataWriter(outStream);
        dataWriter.WriteString("Hello from Test!");
        await dataWriter.StoreAsync();
        dataWriter.DetachStream();
        await outStream.FlushAsync();
        outStream.Dispose(); // 
        fs.Dispose();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多