当前位置:编程学习 > C#/ASP.NET >>

一个结构体保存和窗口位置大小记录的类

 

考完试了,阶段性的休息一下,最近在写一个数据加密软件叫Privacy Data Safe ,这不是一个简单的小软件,而是一个功能十分强大的软件,目前还处于初步的设计阶段,但是一个成功的软件总是在细节考虑得很周到,例如 :记录窗口上次关闭的位置和大小,等等细节,但是技术镀金还是要有个度的,太追求完美势必适得其反,倒不如把这些东西封装在一起,拿来就用

 

不说费话了,先看看这段代码,其实就是把 序列化 和 文件读写 合到一块了

namespace PDSafe.Base

{

    public class Setting

    {

        ///<summary>

        /// 把对象序列化为字节数组

        ///</summary>

        public static byte[] SerializeObject(object obj)

        {

            if (obj == null)

                return null;

            MemoryStream ms = new MemoryStream();

            BinaryFormatter formatter = new BinaryFormatter();

            formatter.Serialize(ms, obj);

            ms.Position = 0;

            byte[] bytes = new byte[ms.Length];

            ms.Read(bytes, 0, bytes.Length);

            ms.Close();

            return bytes;

        }

 

        ///<summary>

        /// 把字节数组反序列化成对象

        ///</summary>

        public static object DeserializeObject(byte[] bytes)

        {

            object obj = null;

            if (bytes == null)

                return obj;

            MemoryStream ms = new MemoryStream(bytes);

            ms.Position = 0;

            BinaryFormatter formatter = new BinaryFormatter();

            try

            {

                obj = formatter.Deserialize(ms);

            }

            catch { obj = null; }

            ms.Close();

            return obj;

        }

 

        public static bool Save(string path, object value, bool isCeranew)

        {

            //如果不存在创建文件

            FileStream fs;

            if ((!File.Exists(path)) && isCeranew)

            {

                try

                {

                    fs = File.Create(path);

                }

                catch

                {

                    return false;

                }

            }

            //如果存在则打开

            else

            {

                try

                {

                    fs = File.Open(path, FileMode.Open, FileAccess.Write);

                }

                catch

                {

                    return false;

                }

 

            }

            //写文件

            byte[] buffer = SerializeObject(value);

 

            try

            {

                for (long i = 0; i < buffer.LongLength; i++)

                    fs.WriteByte(buffer[i]);

            }

            catch

            {

                return false;

            }

            fs.Close();

            return true;

        }

 

   &

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,