Search Unity

  1. If you have experience with import & exporting custom (.unitypackage) packages, please help complete a survey (open until May 15, 2024).
    Dismiss Notice
  2. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice

Read/Write INI file o config file

Discussion in 'Scripting' started by TiTo-to, May 7, 2014.

  1. TiTo-to

    TiTo-to

    Joined:
    Apr 27, 2014
    Posts:
    2
    I find this easy way for read/write some settings to disk, I do not really but google do it :) btw here the code

    Code (csharp):
    1.  
    2. using UnityEngine;
    3. using System;
    4. using System.Collections.Generic;
    5. using System.Linq;
    6. using System.Text;
    7. using System.Runtime.InteropServices;
    8.  
    9. /// <summary>
    10. /// Create a New INI file to store or load data
    11. /// </summary>
    12. public class IniFile : MonoBehaviour
    13. {
    14.     private static string path = Application.dataPath + "/inifile.ini";
    15.  
    16.     [DllImport("kernel32")]
    17.     private static extern long WritePrivateProfileString(string section,
    18.         string key, string val, string filePath);
    19.     [DllImport("kernel32")]
    20.     private static extern int GetPrivateProfileString(string section,
    21.              string key, string def, StringBuilder retVal,
    22.         int size, string filePath);
    23.  
    24.     /// <summary>
    25.     /// Write Data to the INI File
    26.     /// </summary>
    27.     /// <PARAM name="Section"></PARAM>
    28.     /// Section name
    29.     /// <PARAM name="Key"></PARAM>
    30.     /// Key Name
    31.     /// <PARAM name="Value"></PARAM>
    32.     /// Value Name
    33.     public static void IniWriteValue(string Section, string Key, string Value)
    34.     {
    35.         WritePrivateProfileString(Section, Key, Value, path);
    36.     }
    37.  
    38.     /// <summary>
    39.     /// Read Data Value From the Ini File
    40.     /// </summary>
    41.     /// <PARAM name="Section"></PARAM>
    42.     /// <PARAM name="Key"></PARAM>
    43.     /// <PARAM name="Path"></PARAM>
    44.     /// <returns></returns>
    45.     public static string IniReadValue(string Section, string Key)
    46.     {
    47.         StringBuilder temp = new StringBuilder(255);
    48.         //int i = GetPrivateProfileString(Section, Key, "", temp, 255, this.path);
    49.         GetPrivateProfileString(Section, Key, "", temp, 255, path);
    50.         return temp.ToString();
    51.  
    52.     }
    53. }
    54.  
    Is static function so dont need to instantiate everywhere, hope work to u too.
    Remember the right style of ini file is:

    Code (csharp):
    1. [Section]
    2. Key = Value
    that's it...good work.
     
    SamFernGamer4k likes this.
  2. Patico

    Patico

    Joined:
    May 21, 2013
    Posts:
    886
    Good work! But will it work on MacOS / iPhone / Android? I mean, how it sould import kernel32.dll?
    Probably using of Resources.Load() is better way? ;-)
     
  3. Landern

    Landern

    Joined:
    Dec 21, 2008
    Posts:
    354
    It will only work on windows since the unmanaged import is referring to windows dll's which are not available out side of the windows platform.
     
  4. TiTo-to

    TiTo-to

    Joined:
    Apr 27, 2014
    Posts:
    2
    Yhea u right, work on windows only -_-,
    I'm so accustomed to using windows that I forget its restrictions, bad thing, I hate when it happens, do something good means to do something that everyone can use (in this case that all the pc can interpret), at least as I understand the progress ...
    btw I made another one and I think it can also be used by machines that do not speak windows hehe ;)
    right?

    Code (csharp):
    1.  
    2. private static string path = Path.Combine(Application.persistentDataPath, "IniFile.ini");
    3.     private static Dictionary<string, Dictionary<string, string>> IniDictionary = new Dictionary<string, Dictionary<string, string>>();
    4.     private static bool Initialized = false;
    5.     /// <summary>
    6.     /// Sections list
    7.     /// </summary>
    8.     public enum Sections
    9.     {
    10.         Section01,
    11.     }
    12.     /// <summary>
    13.     /// Keys list
    14.     /// </summary>
    15.     public enum Keys
    16.     {
    17.         Key01,
    18.         Key02,
    19.         Key03,
    20.     }
    21.  
    22.     private static bool FirstRead()
    23.     {
    24.         if (File.Exists(path))
    25.         {
    26.             using (StreamReader sr = new StreamReader(path))
    27.             {
    28.                 string line;
    29.                 string theSection = "";
    30.                 string theKey = "";
    31.                 string theValue = "";
    32.                 while (!string.IsNullOrEmpty(line = sr.ReadLine()))
    33.                 {
    34.                     line.Trim();
    35.                     if (line.StartsWith("[")  line.EndsWith("]"))
    36.                     {
    37.                         theSection = line.Substring(1, line.Length - 2);
    38.                     }
    39.                     else
    40.                     {
    41.                         string[] ln = line.Split(new char[] { '=' });
    42.                         theKey = ln[0].Trim();
    43.                         theValue = ln[1].Trim();
    44.                     }
    45.                     if (theSection == "" || theKey == "" || theValue == "")
    46.                         continue;
    47.                     PopulateIni(theSection, theKey, theValue);
    48.                 }
    49.             }
    50.         }
    51.         return true;
    52.     }
    53.  
    54.     private static void PopulateIni(string _Section, string _Key, string _Value)
    55.     {
    56.         if (IniDictionary.Keys.Contains(_Section))
    57.         {
    58.             if (IniDictionary[_Section].Keys.Contains(_Key))
    59.                 IniDictionary[_Section][_Key] = _Value;
    60.             else
    61.                 IniDictionary[_Section].Add(_Key, _Value);
    62.         }
    63.         else
    64.         {
    65.             Dictionary<string, string> neuVal = new Dictionary<string, string>();
    66.             neuVal.Add(_Key.ToString(), _Value);
    67.             IniDictionary.Add(_Section.ToString(), neuVal);
    68.         }
    69.     }
    70.     /// <summary>
    71.     /// Write data to INI file. Section and Key no in enum.
    72.     /// </summary>
    73.     /// <param name="_Section"></param>
    74.     /// <param name="_Key"></param>
    75.     /// <param name="_Value"></param>
    76.     public static void IniWriteValue(string _Section, string _Key, string _Value)
    77.     {
    78.         if (!Initialized)
    79.             FirstRead();
    80.         PopulateIni(_Section, _Key, _Value);
    81.         //write ini
    82.         WriteIni();
    83.     }
    84.     /// <summary>
    85.     /// Write data to INI file. Section and Key bound by enum
    86.     /// </summary>
    87.     /// <param name="_Section"></param>
    88.     /// <param name="_Key"></param>
    89.     /// <param name="_Value"></param>
    90.     public static void IniWriteValue(Sections _Section, Keys _Key, string _Value)
    91.     {
    92.         IniWriteValue(_Section.ToString(), _Key.ToString(), _Value);
    93.     }
    94.  
    95.     private static void WriteIni()
    96.     {
    97.         using (StreamWriter sw = new StreamWriter(path))
    98.         {
    99.             foreach (KeyValuePair<string, Dictionary<string, string>> sezioni in IniDictionary)
    100.             {
    101.                 sw.WriteLine("[" + sezioni.Key.ToString() + "]");
    102.                 foreach (KeyValuePair<string, string> chiave in sezioni.Value)
    103.                 {
    104.                     // value must be in one line
    105.                     string vale = chiave.Value.ToString();
    106.                     vale = vale.Replace(Environment.NewLine, " ");
    107.                     vale = vale.Replace("\r\n", " ");
    108.                     sw.WriteLine(chiave.Key.ToString() + " = " + vale);
    109.                 }
    110.             }
    111.         }
    112.     }
    113.     /// <summary>
    114.     /// Read data from INI file. Section and Key bound by enum
    115.     /// </summary>
    116.     /// <param name="_Section"></param>
    117.     /// <param name="_Key"></param>
    118.     /// <returns></returns>
    119.     public static string IniReadValue(Sections _Section, Keys _Key)
    120.     {
    121.         if (!Initialized)
    122.             FirstRead();
    123.         return IniReadValue(_Section.ToString(), _Key.ToString());
    124.     }
    125.     /// <summary>
    126.     /// Read data from INI file. Section and Key no in enum.
    127.     /// </summary>
    128.     /// <param name="_Section"></param>
    129.     /// <param name="_Key"></param>
    130.     /// <returns></returns>
    131.     public static string IniReadValue(string _Section, string _Key)
    132.     {
    133.         if (!Initialized)
    134.             FirstRead();
    135.         if (IniDictionary.ContainsKey(_Section))
    136.             if (IniDictionary[_Section].ContainsKey(_Key))
    137.                 return IniDictionary[_Section][_Key];
    138.         return null;
    139.     }
    140.  
     
    Last edited: May 9, 2014
    Ghosthowl likes this.
  5. WizzardMaker

    WizzardMaker

    Joined:
    Apr 22, 2015
    Posts:
    5
    BUMB

    For anyone who wants to use this, I corrected some errors of the non-Windows version (compatible with Unity 5.3.2f1):

    Code (CSharp):
    1. using UnityEngine;
    2. using System.Collections;
    3. using System.IO;
    4. using System.Collections.Generic;
    5. using System;
    6.  
    7. public class INIWorker {
    8.     private static string path = Path.Combine(Application.persistentDataPath, "IniFile.ini");
    9.     private static Dictionary<string, Dictionary<string, string>> IniDictionary = new Dictionary<string, Dictionary<string, string>>();
    10.     private static bool Initialized = false;
    11.     /// <summary>
    12.     /// Sections list
    13.     /// </summary>
    14.     public enum Sections {
    15.         Section01,
    16.     }
    17.     /// <summary>
    18.     /// Keys list
    19.     /// </summary>
    20.     public enum Keys {
    21.         Key01,
    22.         Key02,
    23.         Key03,
    24.     }
    25.  
    26.     private static bool FirstRead() {
    27.         if (File.Exists(path)) {
    28.             using (StreamReader sr = new StreamReader(path)) {
    29.                 string line;
    30.                 string theSection = "";
    31.                 string theKey = "";
    32.                 string theValue = "";
    33.                 while (!string.IsNullOrEmpty(line = sr.ReadLine())) {
    34.                     line.Trim();
    35.                     if (line.StartsWith("[") && line.EndsWith("]"))
    36.                     {
    37.                         theSection = line.Substring(1, line.Length - 2);
    38.                     }
    39.                     else
    40.                     {
    41.                         string[] ln = line.Split(new char[] { '=' });
    42.                         theKey = ln[0].Trim();
    43.                         theValue = ln[1].Trim();
    44.                     }
    45.                     if (theSection == "" || theKey == "" || theValue == "")
    46.                         continue;
    47.                     PopulateIni(theSection, theKey, theValue);
    48.                 }
    49.             }
    50.         }
    51.         return true;
    52.     }
    53.  
    54.     private static void PopulateIni(string _Section, string _Key, string _Value) {
    55.         if (IniDictionary.ContainsKey(_Section)) {
    56.             if (IniDictionary[_Section].ContainsKey(_Key))
    57.                 IniDictionary[_Section][_Key] = _Value;
    58.             else
    59.                 IniDictionary[_Section].Add(_Key, _Value);
    60.         } else {
    61.             Dictionary<string, string> neuVal = new Dictionary<string, string>();
    62.             neuVal.Add(_Key.ToString(), _Value);
    63.             IniDictionary.Add(_Section.ToString(), neuVal);
    64.         }
    65.     }
    66.     /// <summary>
    67.     /// Write data to INI file. Section and Key no in enum.
    68.     /// </summary>
    69.     /// <param name="_Section"></param>
    70.     /// <param name="_Key"></param>
    71.     /// <param name="_Value"></param>
    72.     public static void IniWriteValue(string _Section, string _Key, string _Value) {
    73.         if (!Initialized)
    74.             FirstRead();
    75.         PopulateIni(_Section, _Key, _Value);
    76.         //write ini
    77.         WriteIni();
    78.     }
    79.     /// <summary>
    80.     /// Write data to INI file. Section and Key bound by enum
    81.     /// </summary>
    82.     /// <param name="_Section"></param>
    83.     /// <param name="_Key"></param>
    84.     /// <param name="_Value"></param>
    85.     public static void IniWriteValue(Sections _Section, Keys _Key, string _Value) {
    86.         IniWriteValue(_Section.ToString(), _Key.ToString(), _Value);
    87.     }
    88.  
    89.     private static void WriteIni() {
    90.         using (StreamWriter sw = new StreamWriter(path)) {
    91.             foreach (KeyValuePair<string, Dictionary<string, string>> sezioni in IniDictionary) {
    92.                 sw.WriteLine("[" + sezioni.Key.ToString() + "]");
    93.                 foreach (KeyValuePair<string, string> chiave in sezioni.Value) {
    94.                     // value must be in one line
    95.                     string vale = chiave.Value.ToString();
    96.                     vale = vale.Replace(Environment.NewLine, " ");
    97.                     vale = vale.Replace("\r\n", " ");
    98.                     sw.WriteLine(chiave.Key.ToString() + " = " + vale);
    99.                 }
    100.             }
    101.         }
    102.     }
    103.     /// <summary>
    104.     /// Read data from INI file. Section and Key bound by enum
    105.     /// </summary>
    106.     /// <param name="_Section"></param>
    107.     /// <param name="_Key"></param>
    108.     /// <returns></returns>
    109.     public static string IniReadValue(Sections _Section, Keys _Key) {
    110.         if (!Initialized)
    111.             FirstRead();
    112.         return IniReadValue(_Section.ToString(), _Key.ToString());
    113.     }
    114.     /// <summary>
    115.     /// Read data from INI file. Section and Key no in enum.
    116.     /// </summary>
    117.     /// <param name="_Section"></param>
    118.     /// <param name="_Key"></param>
    119.     /// <returns></returns>
    120.     public static string IniReadValue(string _Section, string _Key) {
    121.         if (!Initialized)
    122.             FirstRead();
    123.         if (IniDictionary.ContainsKey(_Section))
    124.             if (IniDictionary[_Section].ContainsKey(_Key))
    125.                 return IniDictionary[_Section][_Key];
    126.         return null;
    127.     }
    128. }
    129.  
     
  6. batman202012

    batman202012

    Joined:
    Jun 13, 2016
    Posts:
    1
    Sorry for bumping this thread again but I was wonder how and where should I call this script? I don't really code a lot in c#, I mostly use unity script.
     
  7. ParsaRt

    ParsaRt

    Joined:
    Jun 30, 2013
    Posts:
    9
    @batman202012 you dont have to put it anywhere because this script have static functions , you just use it , e.g :

    Code (CSharp):
    1. void Start()
    2. {
    3. IniFile.IniWriteValue("Stats","Time",_inTime.ToString());
    4. }
     
    zKici likes this.
  8. zKici

    zKici

    Joined:
    Feb 12, 2014
    Posts:
    438
    So I got a few questions.

    This is certainly very useful, now I just need to figure this out:

    1. How to read all the keys in a section?
    2. How to reference all the keys in a section, and values in a List<string>?
    3. How to now change the values for each referenced keys, values via the changed values from the created list?

    This should be my starting point and I should be able to figure the rest out after that.

    Thank you for the help in advance,

    KZ
     
  9. ZJP

    ZJP

    Joined:
    Jan 22, 2010
    Posts:
    2,649

    HI,

    I use this here : https://forum.unity3d.com/threads/text-to-speech-dll-for-windows-desktop.56038/page-3#post-2410238


    Code (csharp):
    1.  
    2. //
    3. using UnityEngine;
    4. using System.Collections;
    5. using Microsoft.Win32;
    6. using System.Runtime.InteropServices;
    7. //
    8.  
    9. void Start()
    10. {
    11.    // Info (64Bits OS):
    12.    // Executing Windows\sysWOW64\speech\SpeechUX\SAPI.cpl brings up a Window that displays (!) all of the 32 bit Voices
    13.    // and the current single 64 bit Voice "Anna".
    14.  
    15.    // HKEY_LOCAL_MACHINE\\SOFTWARE\Microsoft\Speech\\Voices\\Tokens\\xxxVOICExxxINSTALLEDxxx\\Attributes >>> (Name)
    16.    const string speechTokens = "Software\\Microsoft\\Speech\\Voices\\Tokens";
    17.  
    18.    using (RegistryKey registryKey = Registry.LocalMachine.OpenSubKey(speechTokens))
    19.    {
    20.        VoiceNumber = registryKey.SubKeyCount; // key found not mean true voice number !!!
    21.        VoiceNames  = new string[VoiceNumber + 1];
    22.        VoiceNumber = 0;
    23.  
    24.        foreach (var regKeyFound in registryKey.GetSubKeyNames())
    25.        {
    26.            //Debug.Log(regKeyFound);
    27.            string finalKey = "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Speech\\Voices\\Tokens\\" + regKeyFound + "\\Attributes";
    28.            //Debug.Log(finalKey);
    29.            string gotchaVoiceName = "";
    30.            gotchaVoiceName = (string)Registry.GetValue (finalKey, "Name", "");
    31.  
    32.            if (gotchaVoiceName != "")
    33.            {
    34.                //Debug.Log("Langage Name = " + gotchaVoiceName);
    35.                VoiceNumber++; // increase the real voice number..
    36.                VoiceNames[VoiceNumber ] = gotchaVoiceName;
    37.            }
    38.        }
    39.    }
    40.  
    41.    // return 0 >>> Init ok
    42.    if (VoiceNumber != 0)
    43.    {
    44.        VoiceInit =  Uni_Voice_Init();
    45.    } else VoiceInit = 1;
    46.  
    47. }
    48.  
     
  10. zKici

    zKici

    Joined:
    Feb 12, 2014
    Posts:
    438
    This seems to be something different unless I just simply do not understand it. How can I implement this to read the ini stuff of a file rather than the registry?
     
  11. MagicStyle

    MagicStyle

    Joined:
    Oct 17, 2017
    Posts:
    5
    I just tried it, but it does not work at all.
     
  12. tr1boon

    tr1boon

    Joined:
    Jun 5, 2017
    Posts:
    1
    Works like a charm in 2017.3, a million thanks!