WPF WebBrowser make sure the path or Internet address is correct

 

 

One possible cause is include chinese characters,

 

//Wrong code
private void OpenClick(object sender, RoutedEventArgs e) { OpenFileDialog dialog=new OpenFileDialog(); dialog.Filter = "PDF Files|*.pdf|All Files|*.*"; if(dialog.ShowDialog()==true) { try { string pdfPath = dialog.FileName; if (File.Exists(pdfPath)) { webBrowser.Navigate(pdfPath); } } catch (Exception ex) { MessageBox.Show(ex.Message); } } }

 

 

Solution

 private void OpenClick(object sender, RoutedEventArgs e)
 { 
     OpenFileDialog dialog=new OpenFileDialog();
     dialog.Filter = "PDF Files|*.pdf|All Files|*.*";
     if(dialog.ShowDialog()==true)
     {
         
         try
         {
             string pdfPath = dialog.FileName;
             if (File.Exists(pdfPath))
             {
                 Uri uri = new Uri(pdfPath, UriKind.RelativeOrAbsolute);
                 webBrowser.Navigate(uri);
             }
         }
         catch (Exception ex)
         { 
             MessageBox.Show(ex.Message);
         } 
     }
 }

 

 

The key located at convert string path as Uri 

 Uri uri = new Uri(pdfPath, UriKind.RelativeOrAbsolute);
 webBrowser.Navigate(uri);

 

posted @ 2024-07-12 11:50  FredGrit  阅读(2)  评论(0编辑  收藏  举报