首页 > 代码库 > C# IO

C# IO

<!--文件流-->

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

namespace 文件流
{
    class FileStreamHelper
    {

        public static void Show()
        {
            //实例化文件类(地址,是否新建文件,对文件的控制权限,是否允许多访问)
            FileStream file = new FileStream("../Release/test1.txt", FileMode.Create, FileAccess.ReadWrite, FileShare.None);

            for (int i = 0; i < 100; i++)
            {
                //向文件写入数据
                file.WriteByte((byte)i);
            }

            //重定向文件读取指针
            file.Position = 0;

            for (int i = 0; i < 100; i++)
            {
                //读取文件数据
                Console.Write(file.ReadByte());
            }

            file.Close();

            Console.Read();
        }
    }
}

 

<!--字符流-->

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

namespace 文件流
{
    class TextReadWrite
    {
        public static void Show()
        {
            StreamWriter writer = new StreamWriter("../Release/test2.txt");
            for (int i = 0; i < 10; i++)
            {
                writer.WriteLine("我是第"+ i +"个赢的");
            }
            writer.Close();

            StreamReader reader = new StreamReader("../Release/test2.txt");
            for (string s = reader.ReadLine(); s != null; s = reader.ReadLine())
            {
                Console.WriteLine(s);
            }
            reader.Close();

            Console.Read();
        }
    }
}

 

<!--字节流-->

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;

namespace 文件流
{
    class BinaryReadWrite
    {
        public static void Show()
        {
            //计时类
            Stopwatch sw = new Stopwatch();
            sw.Start();

            BinaryReader br = new BinaryReader(new FileStream("../Release/test3.avi", FileMode.Open, FileAccess.Read));
            BinaryWriter bw = new BinaryWriter(new FileStream("../Release/test3Copy.avi", FileMode.Create, FileAccess.Write));

            byte[] b = new byte[1024 * 8];
            int len = -1;

            while ((len = br.Read(b, 0, 1024 * 8)) > 0)
            {
                bw.Write(b, 0, len);
            }

            br.Close();
            bw.Close();

            sw.Stop();
            //获取所需时间
            Console.WriteLine(sw.ElapsedMilliseconds);    

            Console.Read();
        }
    }
}

 

C# IO