c#IO文件读写操作

来源:互联网 发布:数据库程序设计考试 编辑:程序博客网 时间:2024/05/16 08:07
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;


namespace csharpio
{
    class Program
    {
        static void Main(string[] args)
        {
            //存储文件的路径和文件名
            string file="C:\\Users\\george\\Desktop\\test.txt";
            string[] data=new string[2];
            data[0] = "第一条信息";
            data[1] = "第二条信息";
            ////////写入文件//////
             // System.IO.File.WriteAllLines(file,data);
             //////////读文件//////
            //判断文件是否存在
            if (System.IO.File.Exists(file))
            {
                string[] datast=new string[2];
                //将数据读出来
             //   datast = System.IO.File.ReadAllLines(file);
                //打印数据
              //  Console.WriteLine(datast[0]);
              //  Console.WriteLine(datast[1]);
            }
            //////删除文件//////
            if (System.IO.File.Exists(file))
            {
              //  System.IO.File.Delete(file);
            }


            //////读写bytes//////
             //无论是int float 或者其他类型 都可以转成byte(字节)存入到数组中,然后写入文件,读取回来的时候再转成正确的数据类型进行使用,
            //需要存储的数据
            int   data1 = 100;
            float data2 = 0.1f;
            //记录文件的位置
            int index = 0;
            //用于存储所有数据的byte数组
            byte[] bytes=new byte[256];
            //将data1转换成byte数组
            byte[] b = BitConverter.GetBytes(data1);
            //将data1数据存入bytes数组中
            b.CopyTo(bytes,index);
            //一个int类型占4个byte
            index += 4;
            //将data2转换为byte数组
            b = BitConverter.GetBytes(data2);
            //将data2数据存入bytes数组中
            b.CopyTo(bytes,index);
            //一个float类型占4个byte
            index += 4;
            //将数据进行存储到文件
       //     System.IO.File.WriteAllBytes(file,bytes);


            //判断文件是否存在
            if (System.IO.File.Exists(file))
            {
               bytes=new byte[256];
                //读入数据
               bytes = System.IO.File.ReadAllBytes(file);
                //取出头四个字节作为int
               int reddata1 = BitConverter.ToInt32(bytes,0);
                //取出四个字节作为float
               float reddata2 = BitConverter.ToSingle(bytes,4);
                //打印数据
               Console.WriteLine(reddata1);
               Console.WriteLine("华丽的分割线");
               Console.WriteLine(reddata2);
               
            }


            Console.ReadKey();
            
        }
    }

}


本文题外话: 
我是编程小菜鸟。
 友联:QQ1126291194 

0 0
原创粉丝点击