FileStream操作文件读写

   FileStream fsRead = new FileStream(@"C:\Users\Administrator\Desktop\u.html",FileMode.OpenOrCreate,FileAccess.Read);

            byte[] buffer = new byte[1024 * 1024 * 5];

            //返回本次读取到的有效字节数

           int iNr= fsRead.Read(buffer, 0, buffer.Length);

            //将字节数组中每一个元素按指定编码写成字符串

            string str =Encoding.UTF8.GetString(buffer,0,iNr);

            Console.WriteLine(str);



            //关闭文件

            fsRead.Close();

            //释放资源

            fsRead.Dispose();



            Console.ReadKey();



            //可以自动释放和关闭资源

            using (FileStream fsWrite = new FileStream(@"C:\Users\Administrator\Desktop\u.html", FileMode.OpenOrCreate, FileAccess.Write))

            {

                string strN = "看我把你覆盖掉";

                byte[] buf = Encoding.UTF8.GetBytes(strN);

                fsWrite.Write(buf, 0, buf.Length);

                Console.WriteLine("写入成功");

            }

            Console.ReadKey();

 

你可能感兴趣的:(Stream)