FileStream对文本进行读写操作

    class FileHelper
    {
  

        /// <summary>
        /// 检验文件路径是否合法
        /// </summary>
        /// <param name="path">文件路径</param>
        private static bool CheckPath(string path)
        {
            //正确格式:C:\Users\jcx\Desktop\Test.txt
            string pattern = @"\w{1}:([\\].+)*.+\.\w{3,}";
            Regex rg = new Regex(pattern);
            return rg.IsMatch(path);
        }

        
       /// <summary>
       /// 创建一个新的文本文件
       /// </summary>
        /// <param name="path">文件路径</param>
       /// <param name="content">写入到文本的内容</param>
        public static void CreateNewTxtFile(string path,string content)
        {
            if (!CheckPath(path))
            {
                throw new Exception("文件路径不合法");
            }
            //存在则删除
            if (File.Exists(path))
            {
                File.Delete(path);
            } 

            using (FileStream fs=new FileStream (path,FileMode.CreateNew,FileAccess.Write))
            {
                byte[] bt = Encoding.Default.GetBytes(content);
                fs.Write(bt,0,bt.Length);

            } //using
        }

     
        /// <summary>
       /// 读取文本文件
       /// </summary>
       /// <param name="path">文件路径</param>
       /// <param name="readByte">指定每次读取字节数</param>
        /// <returns>读取的全部文本内容</returns>
        public static string ReadTxtFile(string path,long readByte)
        {
            if (!CheckPath(path))
            {
                throw new Exception("文件路径不合法");
            }

            StringBuilder result = new StringBuilder();
            using (FileStream fs=new FileStream (path,FileMode.Open,FileAccess.Read))
            {
                byte[] bt = new byte[readByte];

                while (fs.Read(bt,0,bt.Length)>0) //每次只从文件中读取部分字节数,一点点读
                {
                    string txt = Encoding.Default.GetString(bt);  //解码转换成字符串
                    result.AppendLine(txt);
                }

            } //using
            return result.ToString();

        }


    }

    class Program
    {
        static void Main(string[] args)
        {

            string path = @"C:\Users\jcx\Desktop\Test.txt";

            FileHelper.CreateNewTxtFile(path, "好好努力");
            string r = FileHelper.ReadTxtFile(path,2);      //2个字节为一个汉字,一个汉字一个汉字的读
            Console.WriteLine(r);

        } // Main



    }

 

posted @ 2018-08-05 14:34  姜承轩  阅读(1283)  评论(0编辑  收藏  举报