文件写入和读取,加密解密,xml例

using UnityEngine;
using System.Collections;
using System.IO;
using System;
using System.Text;
using System.Security.Cryptography;
using System.Xml.Serialization;
using System.Xml;


//文件写入读取
public class FileOperation  {


    private FileOperation() { }
    private static FileOperation instance;
    public static FileOperation Instance
    {
        get
        {
            if (instance == null)
                instance = new FileOperation();
            return instance;
        }
    }


    //写文件 
    public static bool WriteFile_(string filePath, string writeSomething)
    {
        string path = Application.dataPath + "//" + filePath;
        FileInfo file = new FileInfo(path);
        StreamWriter stream;


        if (!file.Exists)
            stream = file.CreateText();  //文件名不存在则创建
        else
            stream = file.AppendText();   //文件名存在则追加
        stream.WriteLine(writeSomething);


        stream.Close();
        stream.Dispose();


        return true;
    }


    //读文件 
    public static string ReadFile_(string filePath)
    {
        string path = Application.dataPath + "//" + filePath;
        FileInfo file = new FileInfo(path);
        string fileData;
        if (file.Exists)
        {
            StreamReader stream = file.OpenText();
            //注意:ReadToEnd 解密会出错 ReadLine不会出错
            fileData = stream.ReadToEnd();   //ReadToEnd全部读取  ReadLine读取第一行  ReadBlock读取指定字符个数
            stream.Close();
            stream.Dispose();


            Debug.Log(fileData);
        }
        else
        {
            Debug.Log("it has not this file");
            return null;
        }


        return fileData;
    }


    //写文件 加密
    public static bool WriteFile_(string filePath,string writeSomething,bool isEncryption)
    {
        string path = Application.dataPath + "//" + filePath;
        FileInfo file = new FileInfo(path);
        StreamWriter stream;
        string fileData;        
        //先对字符串加密
        if (isEncryption)
            fileData = Encrypt(writeSomething);
        else
            fileData = writeSomething;


        if (!file.Exists)
            stream = file.CreateText();  //文件名不存在则创建
        else
            stream = file.AppendText();   //文件名存在则追加
        stream.WriteLine(fileData);


        stream.Close();
        stream.Dispose();


        return true;
    }


    //读文件 解密
    public static string ReadFile_(string filePath,bool isEncryption)
    {
        string path = Application.dataPath + "//" + filePath;
        FileInfo file = new FileInfo(path);
        string fileData;
        if(file.Exists)
        {
            StreamReader stream = file.OpenText();
            //注意:ReadToEnd 解密会出错 ReadLine不会出错
            fileData=stream.ReadLine();   //ReadToEnd全部读取  ReadLine读取第一行  ReadBlock读取指定字符个数
            stream.Close();
            //stream.Dispose();           
            if (isEncryption)
               fileData=Decrypt(fileData);


            Debug.Log(fileData);                       
        }
        else
        {
            Debug.Log("it has not this file");
            return null;
        }


        return fileData;
    }


    /// 加密方法  
    /// 描述: 加密和解密采用相同的key,具体值自己填,但是必须为32位  
    private static string Encrypt(string toE)
    {
        byte[] keyArray = Encoding.UTF8.GetBytes("12348578902223367877723456789012");
        RijndaelManaged rDel = new RijndaelManaged();
        rDel.Key = keyArray;
        rDel.Mode = CipherMode.ECB;
        rDel.Padding = PaddingMode.PKCS7;
        ICryptoTransform cTransform = rDel.CreateEncryptor();
        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toE);
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);


        return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }


    /// 解密方法  
    /// 描述: 加密和解密采用相同的key,具体值自己填,但是必须为32位  
    private static string Decrypt(string toD)
    {
        byte[] keyArray = UTF8Encoding.UTF8.GetBytes("12348578902223367877723456789012");
        RijndaelManaged rDel = new RijndaelManaged();
        rDel.Key = keyArray;
        rDel.Mode = CipherMode.ECB;
        rDel.Padding = PaddingMode.PKCS7;
        ICryptoTransform cTransform = rDel.CreateDecryptor();
        byte[] toEncryptArray = Convert.FromBase64String(toD);
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);


        return UTF8Encoding.UTF8.GetString(resultArray);
    }






    //XML存储和读取


    public static object XmlWriteAndRead(string filePath,object obj)
    {
        if(obj== null)
        {
            Debug.LogError("type is null");
            return null;
        }


        string path = Application.dataPath + "//" + filePath;
        //转换数据类型
        string s = SerializeObject(obj,obj.GetType());


        //创建XML文件且写入数据
        WriteFile_(filePath, s);


        //读取数据
        try
        {
            string xmlData = ReadFile_(filePath);
            return DeserializeObject(xmlData,obj.GetType());
        }
        catch
        {
            Debug.LogWarning("系统读取XML出现错误,请检查");
        }
        return null;
    }


    //数据对象转换成XML字符串
    private static string SerializeObject(object obj, Type type)
    {
        string XmlizedString = null;
        MemoryStream memoryStream = new MemoryStream();
        XmlSerializer xs = new XmlSerializer(type);
        XmlTextWriter xmlTextWriter=new XmlTextWriter(memoryStream,Encoding.UTF8);
        xs.Serialize(xmlTextWriter,obj);
        memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
        XmlizedString = UTF8ByteArrayToString(memoryStream.ToArray());
        return XmlizedString;
    }


    /// xml字符串转换数据对象  
    private static object DeserializeObject(string pXmlizedString, Type ty)
    {
        XmlSerializer xs = new XmlSerializer(ty);
        MemoryStream memoryStream = new MemoryStream(StringToUTF8ByteArray(pXmlizedString));
        XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);
        return xs.Deserialize(memoryStream);
    }
    //UTF8字节数组转字符串  
    private static string UTF8ByteArrayToString(byte[] characters)
    {
        UTF8Encoding encoding = new UTF8Encoding();
        string constructedString = encoding.GetString(characters);
        return (constructedString);
    }


    //字符串转UTF8字节数组  
    private static byte[] StringToUTF8ByteArray(String pXmlString)
    {
        UTF8Encoding encoding = new UTF8Encoding();
        byte[] byteArray = encoding.GetBytes(pXmlString);
        return byteArray;
    }
}
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值