C# 文本文件的读写

// ***********************************************************************
// Assembly         : XXX
// Author           : zhujinrong
// Created          : 05-13-2014
//
// Last Modified By : zhujinrong
// Last Modified On : 05-12-2014
// ***********************************************************************

using System;
using System.IO;

namespace XXX
{
    /// <summary>
    /// 文件操作类
    /// </summary>
    public class BTextFile
    {
        /// <summary>
        /// 读取文件内容
        /// </summary>
        /// <param name="path">文件路径和文件名</param>
        /// <returns>文件内容</returns>
        public static string ReadFile(string path)
        {
            string str = string.Empty;
            try
            {
                using (StreamReader reader = new StreamReader(path))
                {
                    str = reader.ReadToEnd();
                    return str;
                }
            }
            catch (Exception ex)
            {
                Console.Write("读文件错误:" + ex.Message.ToString());
            }

            return str;
        }

        /// <summary>
        /// 写入信息到文件
        /// </summary>
        /// <param name="path">文件路径和文件名</param>
        /// <param name="msg">写入信息</param>
        public static void WriteFile(string path, string msg)
        {
            try
            {
                using (StreamWriter sw = new StreamWriter(path))
                {
                    sw.Write(msg);
                }
            }
            catch (Exception ex)
            {
                Console.Write("写文件错误:" + ex.Message.ToString());
            }
        }

        /// <summary>
        /// 向一个文件末尾追加内容
        /// </summary>
        /// <param name="path">文件的路径和文件名</param>
        /// <param name="msg">追加的消息</param>
        public static void AppendFile(string path, string msg)
        {
            try
            {
                using (StreamWriter sw = File.AppendText(path))
                {
                    sw.Write(msg);
                }
            }
            catch (Exception ex)
            {
                Console.Write("追加文件异常:" + ex.Message.ToString());
            }
        }
    }
}
作者:BestNow
出处:http://www.cnblogs.com/BestNow/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/tianxue/p/3727718.html