I am downloading an epub file online. For this I first created a directory using Directory.CreateDirectory
, then downloaded the file using following code.
WebClient webClient = new WebClient();
webClient.DownloadStringAsync(new Uri(downloadedURL), directoryName);
webClient.DownloadProgressChanged +=
new DownloadProgressChangedEventHandler(ProgressChanged);
webClient.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(Completed);
Is this the correct way of downloading files? What is the code to view the file which is downloaded and displaying it in a grid?
1) You should not use Directory.CreateDirectory
on Windows Phone. Instead, since you are operating on Isolated Storage, you need to use:
var file = IsolatedStorageFile.GetUserStoreForApplication();
file.CreateDirectory("myDirectory");
2) Downloading files can be done through WebClient this way:
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);
}
}
}
Creating a directory directly in this case is optional. If you need to save the file in a nested folder structure, you might as well set the file path to something like /Folder/NewFolder/file.epub.
3) To enumerate files in the Isolated Storage, you could use:
var file = IsolatedStorageFile.GetUserStoreForApplication();
file.GetFileNames();
That's if the files are located in the root of the IsoStore. If those are located inside a directory, you will have to set a search pattern and pass it to GetFileNames
- including the folder name and file type. For every single file, you could use this pattern:
DIRECTORY_NAME\*.*
There is no file. The The DownloadStringCompleted event argument contains a Result member containing a string that is the result of your HTTP request. In the event handler you can refer to this as e.Result
I am unfamiliar with the format of epub files but unless they are strictly text files your code cannot work properly.
You should instead use webclient.OpenReadAsync and the corresponding event, which is similar to DownloadStringAsync in methodology, except that e.Result is a stream you can use to read binary data.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With