【问题标题】:How to retrieve a downloaded file programatically in Windows Phone 7?如何在 Windows Phone 7 中以编程方式检索下载的文件?
【发布时间】:2011-08-02 05:34:03
【问题描述】:

我正在在线下载一个 epub 文件。为此,我首先使用Directory.CreateDirectory 创建了一个目录,然后使用以下代码下载了该文件。

WebClient webClient = new WebClient();
webClient.DownloadStringAsync(new Uri(downloadedURL), directoryName);
webClient.DownloadProgressChanged += 
                   new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadStringCompleted += 
                   new DownloadStringCompletedEventHandler(Completed);

这是下载文件的正确方法吗?查看下载的文件并在网格中显示的代码是什么?

【问题讨论】:

  • 你正在下载什么样的文件?

标签: c# windows-phone-7 download webclient


【解决方案1】:

1) 您不应在 Windows Phone 上使用Directory.CreateDirectory。相反,由于您是在独立存储上操作,因此您需要使用:

var file = IsolatedStorageFile.GetUserStoreForApplication();
file.CreateDirectory("myDirectory");

2)通过WebClient可以通过这种方式下载文件:

WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri("your_URL"));


void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
    var file = IsolatedStorageFile.GetUserStoreForApplication();

    using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream("file.epub", System.IO.FileMode.Create, file))
    {
        byte[] buffer = new byte[1024];
        while (e.Result.Read(buffer, 0, buffer.Length) > 0)
        {
            stream.Write(buffer, 0, buffer.Length);
        }
    }
}

在这种情况下直接创建目录是可选的。如果需要将文件保存在嵌套文件夹结构中,不妨将文件路径设置为 /Folder/NewFolder/file.epub

3) 要枚举独立存储中的文件,您可以使用:

var file = IsolatedStorageFile.GetUserStoreForApplication();
file.GetFileNames();

如果文件位于 IsoStore 的根目录中。如果它们位于目录内,则必须设置搜索模式并将其传递给GetFileNames - 包括文件夹名称和文件类型。对于每个文件,您都可以使用以下模式:

DIRECTORY_NAME\*.*

【讨论】:

  • 谢谢,它帮助我获得了输出。
【解决方案2】:

没有文件。 DownloadStringCompleted 事件参数包含一个 Result 成员,该成员包含一个字符串,该字符串是您的 HTTP 请求的结果。在事件处理程序中,您可以将其称为e.Result

我不熟悉 epub 文件的格式,但除非它们是严格的文本文件,否则您的代码将无法正常工作。

您应该改用 webclient.OpenReadAsync 和相应的事件,这在方法上类似于 DownloadStringAsync,只是 e.Result 是一个可用于读取二进制数据的流。

【讨论】:

  • 感谢您的回复。我将尝试使用 webclient.openreadasync 下载。但是,我的问题是如何检索下载后保存文件的路径。以便可以检查下载的文件
  • 没有文件,在你自己保存之前。一个返回一个字符串,另一个按照 Peter Wone 的建议返回一个 Stream。
猜你喜欢
  • 2013-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-28
  • 1970-01-01
相关资源
最近更新 更多