C# 序列化之文件写入和读取

文件的读取和写入

文件的写入

将对象序列化后存入文件,cmd表示你需要存的文件名,这地方我把存放的位置已经写死了。

 public static void ObjToFile(Object o,String cmd)
        {
            FileStream fs = null;
            BinaryFormatter bf = null;
            try
            {
             fs = new FileStream("C:\\" + cmd + "data.dat", FileMode.Create);
             bf = new BinaryFormatter();
                bf.Serialize(fs, o);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                // throw;
            }
            finally
            {
                if (fs!=null)
                {
                    //关闭Io流
                    fs.Close();
                }
            }   
        }

文件的读取

在这个地方我把文件转成String [] 类型的,这个你们可以改成你们自己所需要的类型就可以。这个地方的cmd是你们读取文件的文件名与上面的cmd是对应的。

  public static Object fileToObj(string cmd)
        {
            String[] s = null;
            FileStream fs = null;
            BinaryFormatter bf = null;
            try
            {
                fs = new FileStream("C:\\" + cmd + "data.dat", FileMode.OpenOrCreate);
                bf = new BinaryFormatter();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                // throw;
            }
            finally
            {
                if (fs != null)
                {
                    s = (string[]) bf.Deserialize(fs);
                    fs.Close();
                }
            }
       return s;
        }
    }

有不足的地方希望大佬门指正![手动狗头]

  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值