對記事本的讀取,這個都很常見,也並不難。如下:
/// <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
}