C# 如何在WindowsPhone7中以编程方式检索下载的文件?

C# 如何在WindowsPhone7中以编程方式检索下载的文件?,c#,windows-phone-7,download,webclient,C#,Windows Phone 7,Download,Webclient,我正在网上下载一个epub文件。为此,我首先使用directory.CreateDirectory创建了一个目录,然后使用以下代码下载了该文件 WebClient webClient = new WebClient(); webClient.DownloadStringAsync(new Uri(downloadedURL), directoryName); webClient.DownloadProgressChanged += new Download

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

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

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

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

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

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

1)您不应该在Windows Phone上使用
目录.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\*.*

您正在下载哪种文件?谢谢您的回复。我将尝试使用webclient.openreadasync下载。但是,我的问题是如何检索下载后保存文件的路径。这样就可以检查下载的文件。在您自己保存之前,这里没有文件。一个返回字符串,另一个按照Peter Wone的建议返回流。谢谢,它帮助我获得了输出。