文件处理封装

  /// <summary>
    /// 文件处理封装
    /// </summary> 
    public static class FileHelper
    {
        /// <summary>
        /// 读取Txt文件
        /// </summary>
        /// <param name="FilePath">文件地址</param>
        /// <returns>文件内容</returns>
        public static string ReadTxtFile(string FilePath)
        {
            if (!File.Exists(FilePath)) throw new Exception("指定的文件不存在或已删除!");
            return File.ReadAllText(FilePath);
        }

        /// <summary>
        /// 往Txt文件写入内容
        /// </summary>
        /// <param name="FilePath"> 文件地址</param>
        /// <param name="Contents">内容</param>
        /// <param name="IsCover"> 是否覆盖原内容</param>
        public static void WriteTxtFile(string FilePath, string Contents, bool IsCover)
        {
            if (!IsCover && File.Exists(FilePath))
            {
                using (StreamReader sr = new StreamReader(FilePath))
                {
                    Contents = sr.ReadToEnd() + " 
" + Contents;
                    sr.Close();
                }
            }
            using (StreamWriter sw = new StreamWriter(FilePath))
            {
                sw.Write(Contents);
                sw.Close();
            }
        }

        /// <summary>
        /// 往Txt文件写入内容
        /// </summary>
        /// <param name="FilePath">文件地址</param>
        /// <param name="Contents">内容</param>
        /// <param name="IsCover">是否覆盖原内容</param>
        public static void WriteTxtFile(string FilePath, string[] Contents, bool IsCover)
        {
            string OldContents = string.Empty;
            if (!IsCover && File.Exists(FilePath))
            {
                using (StreamReader sr = new StreamReader(FilePath))
                {
                    OldContents = sr.ReadToEnd();
                    sr.Close();
                }
            }
            using (StreamWriter sw = new StreamWriter(FilePath))
            {
                sw.WriteLine(OldContents);
                foreach (String str in Contents)
                    sw.WriteLine(str);
                sw.Close();
            }
        }

    }
原文地址:https://www.cnblogs.com/AllUserBegin/p/4424177.html