lena
lena

Reputation: 727

how to view word documents in WPF

I have this code viewing text file documents how can change it to be able to view word documents instead of txt file

 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;
        } 
    }

Upvotes: 2

Views: 5306

Answers (1)

cbr
cbr

Reputation: 13652

You can either use classes found in the Microsoft.Office.Interop.Word namespace or another library. I would suggest the DocX library. The library is lightweight and most importantly does not require Office Word to be installed.

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
    } 
}

Upvotes: 1

Related Questions