C#對word文檔及記事本檔案的讀取

來源:互聯網
上載者:User

對記事本的讀取,這個都很常見,也並不難。如下:

    /// <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
    }

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.