1.CSV文件对应的类:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class UserAccount: GameConfigDataBase
{
public string ID;
public string NickName;
public string Password;
}
- 读取写入数据类:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System;
using System.Reflection;
using UnityEngine.UI;
using System.IO;
using System.Text;
public class GameConfigDataBase
{
static List<string> writeDataList = new List<string>();
public static Dictionary<string, Dictionary<string, GameConfigDataBase>> csvConfigData = new Dictionary<string,Dictionary<string, GameConfigDataBase>>();
public static void ReadGameConfigCsv<T>(string fileName) where T : GameConfigDataBase
{
Dictionary<string, GameConfigDataBase> objDic = new Dictionary<string, GameConfigDataBase>();
string filePath = Application.streamingAssetsPath + "\\" + fileName + ".csv";
string[] lineArray = {};
try
{
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
byte[] byteArray = new byte[1024 * 1024 * 10];
int count = fs.Read(byteArray, 0, byteArray.Length);
string csvStr = Encoding.UTF8.GetString(byteArray, 0, count);
lineArray = csvStr.Split('\n');
fs.Close();
}
}
catch (Exception e)
{
Debug.LogException(e);
return;
}
string[] keyArray = lineArray[2].Split(","[0]);
for (int i = 3; i < lineArray.Length - 1; i++)
{
T configObj = Activator.CreateInstance<T>();
string[] line = lineArray[i].Split(',');
string[] newLine = SplitStrArray(line);
string idValue = "";
if (newLine.Length != 0)
{
line = newLine;
}
for (int j = 0; j < line.Length; j++)
{
string resStr = SetValue<T>(keyArray[j].Trim(), line[j].Trim(), configObj);
if (resStr != "")
{
idValue = resStr;
}
}
objDic.Add(idValue, configObj);
}
GameConfigDataBase.csvConfigData.Add(fileName, objDic);
}
private static string[] SplitStrArray(string[] lineArray)
{
int iCount = 1;
bool isFind = false;
string[] newStrArray = { };
List<string> tempStrList = new List<string>();
List<string> newStrList = new List<string>();
for (int i = 0; i < lineArray.Length; i++)
{
if (lineArray[i].Contains("\""))
{
if (iCount % 2 != 0)
{
isFind = true;
tempStrList.Add(lineArray[i]);
}
else if (iCount % 2 == 0)
{
tempStrList.Add(lineArray[i]);
isFind = false;
string str = String.Join(",", tempStrList.ToArray());
newStrList.Add(str);
tempStrList.Clear();
}
iCount++;
}
else if (isFind)
{
tempStrList.Add(lineArray[i]);
}
else
{
newStrList.Add(lineArray[i]);
}
}
if (iCount != 1)
{
newStrArray = newStrList.ToArray();
}
return newStrArray;
}
public static string SetValue<T>(string fieldName, string fieldValue, T configObj) where T : GameConfigDataBase
{
string idValue = "";
Type type = typeof(T);
foreach (var Field in type.GetFields())
{
if (Field.Name.Equals(fieldName))
{
object setValue = new object();
switch (Field.FieldType.ToString())
{
case "System.Int32":
setValue = int.Parse(fieldValue);
break;
case "System.Int64":
setValue = long.Parse(fieldValue);
break;
case "System.String":
setValue = fieldValue;
break;
case "System.Single":
try
{
setValue = float.Parse(fieldValue);
}
catch (System.Exception e)
{
setValue = 0.0f;
}
break;
default:
Debug.Log("error data type: " + Field.FieldType.ToString());
break;
}
Field.SetValue(configObj, setValue);
if (Field.Name == "ID")
{
idValue = setValue.ToString();
}
}
}
return idValue;
}
public static T GetGameConfigCsv<T>(string fileName, string key) where T : GameConfigDataBase
{
T configObj = null;
if (!csvConfigData.ContainsKey(fileName))
{
return configObj;
}
csvConfigData.Remove(fileName);
ReadGameConfigCsv<T>(fileName);
Dictionary<string, GameConfigDataBase> objDic = csvConfigData[fileName];
if (objDic.ContainsKey(key))
{
configObj = (T)(objDic[key]);
}
return configObj;
}
public static void WriteDataToCsv<T>(string fileName, T configObj) where T : GameConfigDataBase
{
Type typeT = typeof(T);
FieldInfo[] propertyInfos = configObj.GetType().GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (var Field in typeT.GetFields())
{
foreach (FieldInfo pItem in propertyInfos)
{
if (Field.Name.Equals(pItem.Name))
{
object value = pItem.GetValue(configObj);
writeDataList.Add(value.ToString());
}
}
}
string newStr = string.Join(",", writeDataList.ToArray());
string filePath = Application.streamingAssetsPath + "\\" + fileName + ".csv";
using (FileStream fileStream = new FileStream(filePath, FileMode.Append, FileAccess.Write))
{
using (TextWriter textWriter = new StreamWriter(fileStream, Encoding.UTF8))
{
textWriter.WriteLine(newStr);
textWriter.Close();
}
fileStream.Close();
}
writeDataList.Clear();
}
}
3.调用:
UserAccount UserAccountInfo;
GameConfigDataBase.ReadGameConfigCsv<UserAccount>("UserAccount");
UserAccountInfo = GameConfigDataBase.GetGameConfigCsv<UserAccount>("UserAccount", "t123456");
UserAccountInfo = new UserAccount();
UserAccountInfo.ID = accountText.text;
UserAccountInfo.Password = passwordField.text;
UserAccountInfo.NickName = "test01";
GameConfigDataBase.WriteDataToCsv<UserAccount>("UserAccount", UserAccountInfo);
4.CSV文件:
|