AI智能
改变未来

C#学习.FileStream使用

       1.FileStream读取文件

       static void Main(string[] args)
        {
            //FileStream操作字节
            //1.创建FileStream操作对象
            FileStream fs = new FileStream(@\”E:\\1.txt\”,FileMode.OpenOrCreate,FileAccess.ReadWrite);
            byte[] buffer = new byte[1024 * 1024*5];
            //返回本次读取到的有效字节数
            int r = fs.Read(buffer,0,buffer.Length);
            //将字节数组中数据通过指定的编码方式解码成字符串
            string s = Encoding.Default.GetString(buffer,0,r);
            Console.WriteLine(s);
            //关闭流
            fs.Close();
            //释放流所使用的空间
            fs.Dispose();
            Console.ReadLine();
        }

         2. FileStream读取文件    

           //使用using,不用专门去释放资源

            using (FileStream fsWrite = new FileStream(@\”E:\\1.txt\”,FileMode.OpenOrCreate,FileAccess.Write))
            {
                string str = \”看我有没有把你覆盖了\”;
                byte[] buffer = Encoding.Default.GetBytes(str);
                fsWrite.Write(buffer, 0, buffer.Length);
            }
            Console.ReadLine();

      3.将制定文件复制到另外一个路径下

       static void Main(string[] args)
        {
            //将需要复制的多媒体信息读取出来,然后写到指定的位置
            string oldPath = @\”E:\\49.wav\”;
            string newPath = @\”E:\\33.wav\”;
            CopyFile(oldPath, newPath);
            Console.ReadLine();
        }

        public static void CopyFile(string oldPath,string newPath)
        {
            //创建一个负责读取的流
            using (FileStream fsRead = new FileStream(oldPath,FileMode.OpenOrCreate,FileAccess.Read))
            {
                byte[] buffer = new byte[1024 * 1024 * 5];
                //创建一个负责写的流
                using (FileStream fsWrite = new FileStream(newPath, FileMode.OpenOrCreate, FileAccess.Write))
                {

                    white(true)

                    {

                           //返回本次实际获取的字节

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

                            if(r ==0)

                                 break;
                            fsWrite.Write(buffer, 0, r);

                     }
                }
            }          
        }

        4.StreamReader,StreamWriter使用        

        static void Main(string[] args)
        {
            using(StreamReader sr = new StreamReader(@\”E:\\1.txt\”,Encoding.Default))
            {
                while(!sr.EndOfStream)
                {
                    Console.WriteLine(sr.ReadLine());
                }
            }

            using (StreamWriter sw = new StreamWriter(@\”E:\\11.txt\”, true))//true代表以追加方式进行写入
            {
                sw.Write(\”天生我才必有用,千金散尽还复来\”);
            }
            Console.ReadLine();
        }

·

赞(0) 打赏
未经允许不得转载:爱站程序员基地 » C#学习.FileStream使用