Reputation: 358
I am fairly new to Silverlight. I am trying to download a .pdf file (and a couple of other formats) in Silverlight. The user clicks a button, the system goes and gets the URI, then shows a SaveFileDialog to obtain the location to save the file. Here is a code snippet:
WebClient wc = new WebClient();
wc.DownloadStringCompleted += (s, e3) =>
{
if (e3.Error == null)
{
try
{
byte[] fileBytes = Encoding.UTF8.GetBytes(e3.Result);
using (Stream fs = (Stream)mySaveFileDialog.OpenFile())
{
fs.Write(fileBytes, 0, fileBytes.Length);
fs.Close();
MessageBox.Show("File successfully saved!");
}
}
catch (Exception ex)
{
MessageBox.Show("Error getting result: " + ex.Message);
}
}
else
{
MessageBox.Show(e3.Error.Message);
};
wc.DownloadStringAsync("myURI", UriKind.RelativeOrAbsolute));
The file gets saved OK, but it is about twice as big as the original and is unreadable. e3.Result looks about the right size (5Mb), but I suspect it contains a lot of extraneous characters. FileBytes seems to be about two times too big (11Mb). I wanted to try DownloadDataAsync instead of DownloadStringAsync (hoping it would resolve any encoding issues), but Silverlight has a very cut-down version of System.Net.WebClient and does not support DownloadDataAsync (it won't compile).
I am fairly sure it is an encoding problem, but I cannot see how to get around it.
Upvotes: 0
Views: 1767
Reputation: 106796
PDF files are binary and not encoded using UTF8. To download a PDF file using Silverlight you need to use the OpenReadAsync
method of the WebClient
class to start downloading the binary data of the file, and not the DownloadStringAsync
method as you seem to be doing.
Instead of handling the DownloadStringCompleted
event you should handle the OpenReadCompleted
event and write the received bytes to the stream of the local PDF file. If you set the AllowReadStreamBuffering to true
the OpenReadCompleted
event is only fired when the entire file has been downloaded providing you with the same behavior as the DownloadStringCompleted
. However, the entire PDF file will be buffered in memory which may be a bad idea if the file is very large.
Upvotes: 1