2014-11-14 78 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