C#对word文档及记事本文件的读取
对记事本的读取,这个都很常见,也并不难。如下:
/// <summary>
/// 读取记事本
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
private string Txt2Text(string path)
{
StreamReader srFile = null;
string msg = string.Empty;
try
{
srFile = new StreamReader(path, System.Text.Encoding.Default);
msg = srFile.ReadToEnd();
}
catch (Exception ex)
{
msg = ex.Message;
}
finally
{
if (srFile != null)
{
srFile.Dispose();
srFile.Close();
}
}
return msg;
}
对word文档的处理,参考了相关资料,个人觉得以下方法比较好用:
首先要添加引用:Microsoft.Office.Interop.Word;
/// <summary>
/// 读取Word文档
/// </summary>
/// <param name="docFileName"></param>
/// <returns></returns>
public string Doc2Text(string docFileName)
{
#region
string msg = string.Empty;
Microsoft.Office.Interop.Word.ApplicationClass wordApp = null;
Microsoft.Office.Interop.Word.Document doc = null;
object fileobj = null;
object nullobj = null;
try
{
//C#读取word文件之实例化COM
wordApp = new Microsoft.Office.Interop.Word.ApplicationClass();
fileobj = docFileName;
nullobj = System.Reflection.Missing.Value;
//打开指定文件(不同版本的COM参数个数有差异,一般而言除第一个外都用nullobj就行了)
doc = wordApp.Documents.Open(ref fileobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj);
//取得doc文件中的文本
msg = doc.Content.Text;
}
catch (Exception ex)
{
msg = ex.Message;
}
finally
{
if (doc != null)
//C#读取word文件之关闭文件
doc.Close(ref nullobj, ref nullobj, ref nullobj);
if (wordApp != null)
//C#读取word文件之关闭COM
wordApp.Quit(ref nullobj, ref nullobj, ref nullobj);
}
//返回
return msg;
#endregion
}