我正在开发一个应用程序来管理 PDF 文件(不是 PDF 查看器),并且我有一个专用页面来下载具有特定 URL 的 PDF 文件。
我的问题是该应用程序不保存下载的文档。
这是我的应用程序代码(在名为 PDFurl.xaml.cs 的页面类中):
private void Start_Download(object sender, EventArgs e)
{
WebClient PDFdownloader = new WebClient();
DownloadProgress.Visibility = Visibility.Visible;
PDFdownloader.DownloadProgressChanged += new DownloadProgressChangedEventHandler(PDFdownloader_DownloadProgressChanged);
PDFdownloader.OpenReadCompleted += new OpenReadCompletedEventHandler(PDFdownloader_OpenReadCompleted);
PDFdownloader.OpenReadAsync(new Uri(UrlText.Text));
}
void PDFdownloader_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
try
{
DownloadProgress.Value = e.BytesReceived;
DownloadProgress.Maximum = e.TotalBytesToReceive;
}
catch (Exception ex)
{
MessageBox.Show("Download failed!");
}
}
void PDFdownloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
DownloadProgress.Visibility = Visibility.Collapsed;
string[] fileNames = storage.GetFileNames();
foreach (string fileName in fileNames)
{
if (fileName == (SavedFile.Text + ".pdf")) //Save existing file
{
MessageBoxResult rewrite = MessageBox.Show("Already exists a file with this name. Do you want to overwrite it?", "PDF name already used", MessageBoxButton.OKCancel);
if (rewrite == MessageBoxResult.OK)
{
storage.DeleteFile(SavedFile.Text + "pdf");
Save_File(e);
}
else
{
MessageBox.Show("Document not saved!");
e.Result.Close();
DownloadProgress.Value = 0;
DownloadProgress.Visibility = Visibility.Collapsed;
return;
}
}
else //Save new file
{
Save_File(e);
}
}
}
private void Save_File(OpenReadCompletedEventArgs e)
{
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(SavedFile.Text + ".pdf", FileMode.Create, storage))
{
byte[] buffer = new byte[1024];
while (e.Result.Read(buffer, 0, buffer.Length) > 0)
{
stream.Write(buffer, 0, buffer.Length);
}
MessageBox.Show("File downloaded and saved successfully!");
foreach (string file in storage.GetFileNames())
{
MessageBox.Show("Found " + file);
}
}
}
我包含了一些消息框来监视每个任务,但是当它显示成功下载的消息时,它并没有真正保存任何东西。