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());
            }
        }
    }
}

 

posted on 2014-05-14 14:44  BestNow  阅读(242)  评论(0编辑  收藏  举报

导航