C#中Ini文件读写操作

来源:互联网 发布:网络的拓扑结构 编辑:程序博客网 时间:2024/06/06 02:57
1 INI文件的格式
C#读写ini文件其实并不是普通的文本文件.它有自己的结构.由若干段落(SECTION)组成,在每个带括号的标题下面,是若干个以单个单词开头的关键字(KEYWORD)和一个等号,等号右边就是关键字的值(VALUE).例如:
  1. [Section1]  
  2.     KeyWord1 = Value1  
  3.     KeyWord2 = Value2  
  4.     ...  
  5. [Section2]  
  6.     KeyWord3 = Value3  
  7.     KeyWord4 = Value4 
虽然C#中没有,但是在"kernel32.dll"这个文件中有Win32的API函数--WritePrivateProfileString()和GetPrivateProfileString()
C#读写ini文件实现之C#声明INI文件的写操作函数WritePrivateProfileString():
  1. [DllImport( "kernel32" )]  
  2.   private static extern long WritePrivateProfileString (
  3.  string section ,string key , string val   
  4. string filePath ) ; 
参数说明:
section:INI文件中的段落;
key:INI文件中的关键字;
val:INI文件中关键字的数值;
filePath:INI文件的完整的路径和名称。
C#读写ini文件实现之C#申明INI文件的读操作函数GetPrivateProfileString():
  1. [DllImport("kernel32")]  
  2.  private static extern int GetPrivateProfileString (
  3.  string section ,  
  4.   string key , string def , StringBuilder retVal ,  
  5.   int size , string filePath ) ; 
参数说明:
section:INI文件中的段落名称;
key:INI文件中的关键字;
def:无法读取时候时候的缺省数值;
retVal:读取数值;
size:数值的大小;
filePath:INI文件的完整路径和名称。
using System;using System.IO;using System.Runtime.InteropServices;using System.Text;using UnityEngine;internal class IniFiles{    public string FileName;    public IniFiles()    {    }    public IniFiles(string AFileName)    {        FileInfo info = new FileInfo(AFileName);        if (!info.Exists)        {            StreamWriter writer = new StreamWriter(AFileName, false, Encoding.Unicode);            try            {                writer.Write("#配置文件");                writer.Close();            }            catch            {                throw new ApplicationException("ini文件不存在");            }        }        this.FileName = AFileName;    }    ~IniFiles()    {        this.UpdateFile();    }    [DllImport("kernel32", CharSet = CharSet.Unicode)]    private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath);    public float ReadFloat(string Section, string Ident, float Default)    {        string str = this.ReadString(Section, Ident, Convert.ToString(Default));        try        {            return Convert.ToSingle(str);        }        catch (Exception exception)        {            Debug.LogError(exception.Message);            return Default;        }    }    public int ReadInteger(string Section, string Ident, int Default)    {        string str = this.ReadString(Section, Ident, Convert.ToString(Default));        try        {            return Convert.ToInt32(str);        }        catch (Exception exception)        {            Debug.LogError(exception.Message);            return -1;        }    }    public string ReadString(string Section, string Ident, string Default)    {        byte[] retVal = new byte[0x80];        GetPrivateProfileString(Section, Ident, Default, retVal, retVal.Length, this.FileName);        string str = Encoding.Unicode.GetString(retVal);        str.Trim();        return str;    }    public void UpdateFile()    {        WritePrivateProfileString(null, null, null, this.FileName);    }    public void WriteFloat(string Section, string Ident, float Value)    {        this.WriteString(Section, Ident, Value.ToString());    }    public void WriteInteger(string Section, string Ident, int Value)    {        this.WriteString(Section, Ident, Value.ToString());    }    [DllImport("kernel32", CharSet = CharSet.Unicode)]    private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath);    public void WriteString(string Section, string Ident, string Value)    {        if (!WritePrivateProfileString(Section, Ident, Value, this.FileName))        {            throw new ApplicationException("写Ini文件出错");        }    }    public string IniPath    {        get        {            return this.FileName;        }        set        {            this.FileName = value;        }    }    public bool IsExit    {        get        {            FileInfo info = new FileInfo(this.FileName);            return info.Exists;        }    }}
以上是对INI文件的读写操作,然后在使用的地方实现这个类的方法就可以了
以下是读取配置文件,然后存入一个Dictionary,直接去Dictionary值就行了
using System;using System.Collections.Generic;using System.IO;using System.Runtime.InteropServices;using UnityEngine;public class VR_Configuration : MonoBehaviour{    private enum WINDOWLOC    {        LEFTUP,        CENTER    }    private const uint SWP_SHOWWINDOW = 64u;    private const int GWL_STYLE = -16;    private const int WS_BORDER = 1;    [SerializeField]    public string productName = "输入PlayerSettings中ProductName的值";    private string wndclass = "UnityWndClass";    [SerializeField]    public string configName = "Config.ini";    [SerializeField]    public Rect fullScreenVec2;    [SerializeField]    public Rect windowScreenVec2;    private IntPtr windowIndex;    private VR_Configuration.WINDOWLOC windowLoc;    private IniFiles Ini;    //  申明Dictionary 用来保存INI文件的key=value    public Dictionary<string, float> CONTROLLERSETVR = new Dictionary<string, float>(3);    public Dictionary<string, float> ADDITIONVALUE = new Dictionary<string, float>(5);    public Dictionary<string, int> COM = new Dictionary<string, int>(2);    private int cxScreen;    private int cyScreen;    private bool IsFullScreen = true;    public bool IsExit    {        get        {            return this.Ini.IsExit;        }    }    [DllImport("user32.dll", CharSet = CharSet.Unicode, EntryPoint = "MessageBoxW")]    private static extern int MsgBoxW(IntPtr hWnd, string text, string caption, uint type);    [DllImport("user32.dll", CharSet = CharSet.Unicode)]    private static extern IntPtr SetWindowLong(IntPtr hwnd, int _nIndex, int dwNewLong);    [DllImport("user32.dll", CharSet = CharSet.Unicode)]    private static extern bool SetWindowPos(IntPtr hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);    [DllImport("user32.dll")]    private static extern IntPtr FindWindow(string lpClassName, string lpWindowName);    [DllImport("user32")]    private static extern int GetSystemMetrics(int nIndex);    private void Awake()    {        this.windowIndex = VR_Configuration.FindWindow(this.wndclass, this.productName);        string text = Path.GetDirectoryName(Application.dataPath) + Path.AltDirectorySeparatorChar + this.configName;        this.cxScreen = VR_Configuration.GetSystemMetrics(0);        this.cyScreen = VR_Configuration.GetSystemMetrics(1);        if (!File.Exists(text))        {            //Ini 写入操作,初始化INI文件            this.Ini = new IniFiles(text);            this.Ini.WriteInteger("SETTING", "FullScreen", 1);            this.Ini.WriteInteger("SETTING", "FullWidth", this.cxScreen);            this.Ini.WriteInteger("SETTING", "FullHeight", this.cyScreen);            this.Ini.WriteInteger("SETTING", "WindowLocation", 0);            this.Ini.WriteInteger("COM", "Num", 1);            this.Ini.WriteFloat("CONTROLLERSETVR", "Center", 123f);            this.Ini.WriteFloat("CONTROLLERSETVR", "MoveSpeed", 0.2f);            this.Ini.WriteFloat("CONTROLLERSETVR", "RotateSpeed", 3f);            this.Ini.WriteFloat("CONTROLLERSETVR", "Dir", 1f);            this.Ini.WriteFloat("ADDITIONVALUE", "AddFloat1", 1f);            this.Ini.WriteFloat("ADDITIONVALUE", "AddFloat2", 2f);            this.Ini.WriteFloat("ADDITIONVALUE", "AddFloat3", 3f);            this.Ini.WriteFloat("ADDITIONVALUE", "AddFloat4", 4f);            this.Ini.WriteFloat("ADDITIONVALUE", "AddFloat5", 5f);        }        else        {            this.Ini = new IniFiles();            this.Ini.IniPath = text;        }        // 初始化Dictionary,读取        this.fullScreenVec2.width=((float)this.Ini.ReadInteger("SETTING", "FullWidth", 0));        this.fullScreenVec2.height=((float)this.Ini.ReadInteger("SETTING", "FullHeight", 0));        this.COM.Add("Num", this.Ini.ReadInteger("COM", "Num", 1));        this.CONTROLLERSETVR.Add("Center", this.Ini.ReadFloat("CONTROLLERSETVR", "Center", 100f));        this.CONTROLLERSETVR.Add("MoveSpeed", this.Ini.ReadFloat("CONTROLLERSETVR", "MoveSpeed", 1f));        this.CONTROLLERSETVR.Add("RotateSpeed", this.Ini.ReadFloat("CONTROLLERSETVR", "RotateSpeed", 1f));        this.CONTROLLERSETVR.Add("Dir", this.Ini.ReadFloat("CONTROLLERSETVR", "Dir", 1f));        this.ADDITIONVALUE.Add("AddFloat1", this.Ini.ReadFloat("ADDITIONVALUE", "AddFloat1", 0f));        this.ADDITIONVALUE.Add("AddFloat2", this.Ini.ReadFloat("ADDITIONVALUE", "AddFloat2", 0f));        this.ADDITIONVALUE.Add("AddFloat3", this.Ini.ReadFloat("ADDITIONVALUE", "AddFloat3", 0f));        this.ADDITIONVALUE.Add("AddFloat4", this.Ini.ReadFloat("ADDITIONVALUE", "AddFloat4", 0f));        this.ADDITIONVALUE.Add("AddFloat5", this.Ini.ReadFloat("ADDITIONVALUE", "AddFloat5", 0f));    }    private void Start()    {       // 设置屏幕分辨率        if (this.Ini.ReadInteger("SETTING", "FullScreen", 0) == -1)        {            VR_Configuration.MsgBoxW(this.windowIndex, "请检查是否写入屏幕参数或者写入的是正整数!\n写入格式:FullWidth = 1024 FullHeight = 768", "读取假全屏参数错误", 16u);            Application.Quit();        }        if (this.Ini.ReadInteger("SETTING", "FullScreen", -1) == 1)        {            Screen.SetResolution((int)this.fullScreenVec2.width, (int)this.fullScreenVec2.width, false);            this.IsFullScreen = true;        }        if (this.Ini.ReadInteger("SETTING", "FullScreen", 0) == 0)        {            Screen.SetResolution((int)this.windowScreenVec2.width, (int)this.windowScreenVec2.height, false);        }        this.windowLoc = (VR_Configuration.WINDOWLOC)this.Ini.ReadInteger("SETTING", "WindowLocation", 0);        switch (this.windowLoc)        {            case VR_Configuration.WINDOWLOC.LEFTUP:                this.fullScreenVec2.x=0f;                this.fullScreenVec2.y=0f;                this.windowScreenVec2.x=0f;                this.windowScreenVec2.y=0f;                return;            case VR_Configuration.WINDOWLOC.CENTER:                this.fullScreenVec2.center=new Vector2((float)this.cxScreen * 0.5f, (float)this.cyScreen * 0.5f);                this.windowScreenVec2.center=this.fullScreenVec2.center;                return;            default:                return;        }    }    private void Update()    {        if (this.IsFullScreen)        {            VR_Configuration.SetWindowLong(this.windowIndex, -16, 1);            VR_Configuration.SetWindowPos(this.windowIndex, -1, (int)this.fullScreenVec2.x, (int)this.fullScreenVec2.y, (int)this.fullScreenVec2.width, (int)this.fullScreenVec2.height, 64u);        }        if (Input.GetKeyDown(KeyCode.Space))        {            Application.Quit();        }    }}

然后使用的地方直接获取:GameObject.Find("GameObject").GetComponent<VR_Configuration>().COM["Num"];
开始的时候我们把脚本绑定到物体上

运行后会Ini配置文件

至此读取配置INI就over
Path.AltDirectorySeparatorChar 如果用‘’
原创粉丝点击