我有这个代码查看文本文件文件如何更改它以便能够查看word文档而不是txt文件
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 :(得分: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
}
}