2014-11-14 79 views
1

我有這樣的代碼查看文本文件的文件如何可以改變它才能夠查看Word文檔而不是txt文件如何查看Word文檔中的WPF

private void button1_Click(object sender, RoutedEventArgs e) 
    { 
     // Create OpenFileDialog 
     Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); 

     // Set filter for file extension and default file extension 
     dlg.DefaultExt = ".txt"; 
     dlg.Filter = "Text documents (.txt)|*.txt"; 

     // Display OpenFileDialog by calling ShowDialog method 
     Nullable<bool> result = dlg.ShowDialog(); 

     // Get the selected file name and display in a TextBox 
     if (result == true) 
     { 
      // Open document 
      string filename = dlg.FileName; 
      FileNameTextBox.Text = filename; 

      Paragraph paragraph = new Paragraph(); 
      paragraph.Inlines.Add(System.IO.File.ReadAllText(filename)); 
      FlowDocument document = new FlowDocument(paragraph); 
      FlowDocReader.Document = document; 
     } 
    } 
+0

不,我想打開打開文件對話框,並從中選擇文件的Word文檔,就像我的代碼,但。我不知道轉換的代碼才能夠查看Word文檔 – lena

+0

是的,但對於開放的方法,並從閱讀Word文件是一樣的。 – cubrr

+0

是的,我看到了,但我想用OpenFileDialog,謝謝你的努力 – lena

回答

1

您可以在Microsoft.Office.Interop.Word命名空間中使用類或另一個圖書館。我會建議DocX library。該庫是輕量級的,最重要的是不需要安裝Office Word。

using Novacode; 
// ... 
private void button1_Click(object sender, RoutedEventArgs e) 
{ 
    // Create OpenFileDialog 
    Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); 

    // Set filter for file extension and default file extension 
    dlg.DefaultExt = ".doc"; 
    dlg.Filter = "Word documents|*.doc;*.docx"; 

    // Display OpenFileDialog by calling ShowDialog method 
    Nullable<bool> result = dlg.ShowDialog(); 

    // Get the selected file name and display in a TextBox 
    if (result == true) 
    { 
     // Open document 
     string filename = dlg.FileName; 
     FileNameTextBox.Text = filename; 

     var document = DocX.Load(filename); 

     string contents = document.Text; 

     // Use the file 
    } 
} 
+0

謝謝你,但是erroe發現document = DocX.Load(filename); string contents = document.Text; – lena

+0

@ user3120051您遇到什麼錯誤? – cubrr

+0

紅線下的文件和DocX – lena