Converting a .doc file to .txt file using CSharp.NETIn this article I am going to show, how you can easily convert a .doc file to .txt file or in other format.
For this you have add a reference of Microsoft.Office.Interop.Word in your application.
Following is the function that I used to convert
/// <summary>
/// Function to convert .doc file to .txt file
/// </summary>
/// <param name="fileName">filename is name of file you want to convert and it include full path of the file</param>
/// <returns>return true if success or file with .txt is already there and false if any error occure</returns>
public static bool ConvertToText(string fileName)
{
try
{
// specifying the Source & Target file names
object Source = fileName;
object Target = fileName.Replace(".doc", ".txt");
if (!File.Exists(fileName.Replace(".doc", ".txt")))
{
//Creating the instance of Word Application
Microsoft.Office.Interop.Word.Application newApp = new Microsoft.Office.Interop.Word.Application();
// Use for the parameter whose type are not known or
// say Missing
object Unknown = Type.Missing;
// Source document open here
// Additional Parameters are not known so that are
// set as a missing type
newApp.Documents.Open(ref Source, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown, ref Unknown, ref Unknown);
// Specifying the format in which you want the output file
object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatText;
//Changing the format of the document
newApp.ActiveDocument.SaveAs(ref Target, ref format,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown);
// for closing the application
newApp.Quit(ref Unknown, ref Unknown, ref Unknown);
}
return true;
}
catch (Exception ex)
{
throw ex;
return false;
}
}
Note: If you want to convert in other format then change the target file extension and following line of code like if I want file in rich text format then code would be as follow:
object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatRTF;
Thanks and happy coding!!!