You can use Microsoft.Office.Interop.Word to do this, a simple example:
private void browseBtn_Click(object sender, EventArgs e)
{
string filePath = null;
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = "d:\\";
openFileDialog.Filter = @"All Files|*.txt;*.docx;*.doc;";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//Get the path of specified file
filePath = openFileDialog.FileName;
//Read the contents of the file into a stream
var fileStream = openFileDialog.OpenFile();
}
}
Word.Application application = new Word.Application();
Document document = application.Documents.Open(filePath);
List<string> text = GeyText(document);
textBox1.Text = text[0];
textBox2.Text = text[1];
document.Close();
application.Quit();
}
private List<string> GeyText(Document document)
{
List<string> strings = new List<string>();
StringBuilder boldText = new StringBuilder();
StringBuilder italicText = new StringBuilder();
foreach (Range item in document.Words)
{
if (item.Bold == -1)
{
boldText.Append(item.Text + Environment.NewLine);
}
if (item.Italic == -1)
{
italicText.Append(item.Text + Environment.NewLine);
}
}
strings.Add(boldText.ToString());
strings.Add(italicText.ToString());
return strings;
}
If the response is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.