asp.net Microsoft Word file is encrypted and you can’t extract the meaningful text by just reading the file with IOStream. In this quick tutorial, I will tell you that how you can read content from a .doc or .docx file in C#.

Step 1:-

Create new Windows Application project in visual studio and make the following GUI:

image

Step 2:-

Add Microsoft Word 12.0 object library as a reference.

image

Step 3:-

Now write the following code behind the select file button’s click event.

        private void select_file_Click(object sender, EventArgs e)
        {
            try
            {
                OpenFileDialog path = new OpenFileDialog();
                //making an object for the OpenFileDialog
                path.Title = "Tauqeer Sample";
                path.InitialDirectory = @"c:\";
                path.RestoreDirectory = true;

                if (path.ShowDialog() == DialogResult.OK)
                {
                    textBox1.Text = path.FileName.ToString();
                }
            }
            catch (Exception l)
            {
                MessageBox.Show(l.Message);
            }
        }

Step 4:-

Now write this code behind the show file button’s click event.

        private void show_Click(object sender, EventArgs e)
        {
            try
            {
                Microsoft.Office.Interop.Word.ApplicationClass wordObject = new ApplicationClass();
                object file = textBox1.Text; //this is the path
                object nullobject = System.Reflection.Missing.Value;
                Microsoft.Office.Interop.Word.Document docs = wordObject.Documents.Open
                    (ref file, ref nullobject, ref nullobject, ref nullobject,
                    ref nullobject, ref nullobject, ref nullobject, ref nullobject,
                    ref nullobject, ref nullobject, ref nullobject, ref nullobject,
                    ref nullobject, ref nullobject, ref nullobject, ref nullobject
                                    );
                docs.ActiveWindow.Selection.WholeStory();
                docs.ActiveWindow.Selection.Copy();
                IDataObject data = Clipboard.GetDataObject();
                textBox2.Text = data.GetData(DataFormats.Text).ToString();
                docs.Close(ref nullobject, ref nullobject, ref nullobject);
            }
            catch (Exception j)
            {
                MessageBox.Show(j.Message);
            }
        }

Your done! run it…here is the final screenshot of the program.

image