• C#之读写文件学习案例


    //读文件
    /*using System.IO;
    using System;
    using System.Windows.Forms;    //包含MessageBox();函数
    public class readFileExample
    {
        public static void Main()
        {
            //定义一个一维数组,并初始化数据
            byte[] buf1 = new byte[] { 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82 };
            FileStream s = new FileStream("foot.dat", FileMode.Create);  //如果没有相应的文件,则创建
            s.Write(buf1, 0, buf1.Length);    //将数组中的数据写入流中
            s.Close();           //操作完成关闭流
            s = new FileStream("foot.dat", FileMode.Open);     //打开相应的文件
            int i;
            string str = "";
            if (s.CanRead)     //判断文件是否可读
            {
                for (; (i = s.ReadByte()) != -1; )     //一次读一个字节,一个数为一个字节
                {
                    
                    str += (char)i;               //将读到的内容强制转换为字符类型并串连起来
                }
            }
            s.Close();     //关闭文件
            MessageBox.Show(str, "输出结果");
        }
    }*/
    using System;
    using System.IO;
    using System.Windows.Forms;
    public class WriteFileExample
    {
        public static void Main()
        {
           //定义一个一维数组并初始化数据
            byte[] buf = new byte[] { 97, 98, 99, 100, 101 };
            Stream s = new FileStream("foot.dat", FileMode.Append, FileAccess.Write);//文件的访问方式为写,且添加非覆盖
            s.Write(buf, 0, buf.Length);
            s.Close();             //写进程必须关闭才能访问,否则出现异常错误
            s = new FileStream("foot.dat", FileMode.Open, FileAccess.Read);
            int i;
            string str = "";
            if (s.CanRead)
            {
                for (; (i = s.ReadByte()) != -1; )
                {
                    str += (char)i;
                }
            }
            s.Close();
            MessageBox.Show(str, "输出结果");
        }
    }

  • 相关阅读:
    Linux创建删除文件和文件夹
    Linux操作大全
    CentOS7从一般用户切换到root用户
    Eclipse一直building workspace问题解决
    maven项目启动找不到org.springframework.web.context.ContextLoaderListener
    java中如何补齐汉字字符
    java中如何根据函数查询引用的jar包
    delphi中Tkbmmemtable数据转成SQL脚本
    java设计模式(一)——单例模式
    UMl类图基本认识
  • 原文地址:https://www.cnblogs.com/zztong/p/6695219.html
Copyright © 2020-2023  润新知