读写文件

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace FileStreamRead
{
    class StreamReadDemo01
    {
        public StreamReadDemo01() { }
        /// <summary>
        /// 一个字节一个字节的读
        /// </summary>
        public void ReadFile()
        {
            FileStream fs;
            string enPath = Environment.CurrentDirectory.Substring(0, Environment.CurrentDirectory.Length - 9);
            string readPath = enPath + "TextFile1.txt";

            fs = new FileStream(readPath, FileMode.Open);
            long left = fs.Length;
            byte[] bt = new byte[100];//一点一点读取数据很好,就是字的大小不好控制
            //char[] bt = new char[100];
            int maxLength = bt.Length;
            int start = 0;
            int num = 0;
            while (left > 0)
            {
                fs.Position = start;
                num = 0;
                if (left < maxLength)
                {
                    num = fs.Read(bt, 0, Convert.ToInt32(left));
                }
                else
                {
                    num = fs.Read(bt, 0, maxLength);
                }
                if (num == 0)
                {
                    break;
                }
                start += num;
                left -= num;
                Console.Write(Encoding.UTF8.GetString(bt));
            }
            fs.Close();
        }
        string readLine = "";
        /// <summary>
        /// 一行一行的读
        /// </summary>
        public void StringRead()
        {
            string enPath = Environment.CurrentDirectory.Substring(0, Environment.CurrentDirectory.Length - 9);
            string readPath = enPath + "TextFile1.txt";
            StreamReader sr = new StreamReader(readPath, Encoding.GetEncoding("GB2312"));

            string line;
            //string readLine="";
            while ((line = sr.ReadLine()) != null)
            {
                readLine += line.ToString() + "
";
            }
            Console.Write(readLine);
            sr.Close();
        }
        /// <summary>
        /// 写文件
        /// </summary>
        public void StringWriter()
        {
            string enPath = Environment.CurrentDirectory.Substring(0, Environment.CurrentDirectory.Length - 9);
            string readPath = enPath + "TextFile2.txt";
            StreamWriter sw = new StreamWriter(readPath,true, Encoding.UTF8);
           // sw.WriteLine(readLine);
            sw.Write(readLine);//这两句读出来几乎一模一样
            sw.Close();
        }
    }
}
原文地址:https://www.cnblogs.com/zhao123/p/3475022.html