This article presents how to create a Windows Forms application to open and close your Word files using Spire.DocViewer component. Detailed steps would be as follows:
First of all, download Spire.DocViewer, add DocViewer Control to VS Toolbox.
Then create a Windows Forms application, design your Form1 as below.
- Add 'Open from file' button to open a file from existing Word document.
- Add 'Open from stream' button to load a Word file from steam.
- Add 'Close' button to shut down the open file.
- Drag 'DocDocumentViewer Control' into Form1, which is used to display Word document.
Code Snippet:
Step 1: Initialize components in Form1.
System.IO.FileStream stream; public Form1() { InitializeComponent(); }
Step 2: Create an OpenFileDialog to select the correct file type that we want to load, otherwise error message 'Cannot detect current file type' will occur.
private void btnOpen_Click(object sender, EventArgs e) { //open a DOC document OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "Word97-2003 files(*.doc)|*.doc|Word2007-2010 files (*.docx)|*.docx|All files (*.*)|*.*"; dialog.Title = "Select a DOC file"; dialog.Multiselect = false; dialog.InitialDirectory = System.IO.Path.GetFullPath(@"..\..\..\..\..\..\Data"); DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { try { //Load DOC document from file. this.docDocumentViewer1.LoadFromFile(dialog.FileName); } catch (Exception ex) { MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
Step 3: This button code enables users to open Word files from a stream in Xml or Microsoft Word format.
private void btnOpenStream_Click(object sender, EventArgs e) { //open a doc document OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "Word97-2003 files(*.doc)|*.doc|Word2007-2010 files (*.docx)|*.docx|All files (*.*)|*.*"; dialog.Title = "Select a DOC file"; dialog.Multiselect = false; dialog.InitialDirectory = System.IO.Path.GetFullPath(@"..\..\..\..\..\..\Data"); DialogResult result = dialog.ShowDialog(); if (result == DialogResult.OK) { try { string docFile = dialog.FileName; stream = new System.IO.FileStream(docFile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); if (stream != null) { //Load doc document from stream. this.docDocumentViewer1.LoadFromStream(stream, Spire.Doc.FileFormat.Auto); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error!", MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
Step 4: Close the open file.
private void btnClose_Click(object sender, EventArgs e) { //Close current doc document. this.docDocumentViewer1.CloseDocument(); }
After running the code, I opened a test file with this Windows application. Here is the screenshot of effect: