Skip to content
Snippets Groups Projects
IniParser.cs 6.78 KiB
/*
  .Ini file Parser
  Author: Tristan 'Kennyist' Cunningham - www.tristanjc.com
  Date: 13/04/2014
  License: Creative commons ShareAlike 3.0 - https://creativecommons.org/licenses/by-sa/3.0/
*/

using UnityEngine;
using System.Collections;
using System.IO;

namespace Shared.ConfigSetter {
  /// <summary>
  /// An .ini file parser that Creates and edits .ini files, With functions to fetch and delete values.
  /// </summary>
  public class IniParser {

    private ArrayList keys = new ArrayList();
    private ArrayList vals = new ArrayList();
    private ArrayList comments = new ArrayList();

    private string path = Application.dataPath + "/../Config/";

    /// <summary>
    /// Initializes a new instance of the <see cref="IniParser"/> class without loading a file.
    /// </summary>
    public IniParser(string relativePathToConfigFile){
      //Debug.Log("Current directory: " + Directory.GetCurrentDirectory());
      //Debug.Log("Application persistent data path: " + Application.persistentDataPath);
      //Debug.Log("Application data path: " + Application.dataPath);
      path = relativePathToConfigFile;
		  if (!Directory.Exists(path)) {
			  Directory.CreateDirectory(path);
		  }
    }

    /// <summary>
    /// Initializes a new instance of the <see cref="IniParser"/> class with loading a file.
    /// </summary>
    /// <param name="file">Name of the file you want to load.</param>
    public IniParser(string file, string relativePathToConfigFile){
      path = relativePathToConfigFile;
		  if (!Directory.Exists(path)) {
			  Directory.CreateDirectory(path);
		  }

      Load(file);
    }

    /// <summary>
    /// Removes data where the key does not match the prefix
    /// </summary>
    /// <param name="prefix">The string to match before the delimiting ':' character</param>
    public void PruneUsingKeyPrefix(string prefix) {
      for (int i = keys.Count - 1; i >= 0; --i) {
        string key = keys[i].ToString();
        string[] splitKey = key.Split(':');

        if (!splitKey[0].Contains(prefix)) {
          keys.RemoveAt(i);
          vals.RemoveAt(i);
          comments.RemoveAt(i);
        } else {
          keys[i] = splitKey[1];
        }
      }
    }

    /// <summary>
    /// Returns true if the file exists, or false if it doesnt.
    /// </summary>
    /// <param name="file">The selected file.</param>
    public bool DoesExist(string file){
      //return File.Exists(Application.persistentDataPath + "/" + file + ".ini") ? true : false;    
      return File.Exists(GetFullPath(file)) ? true : false;
    }

  
    public string GetFullPath(string rootFileName) {
      return System.IO.Path.Combine(path, rootFileName + ".ini");
    }

    /// <summary>
    /// Set the variable and value if they dont exist. Updates the variables value if does exist.
    /// </summary>
    /// <param name="key">The variable name</param>
    /// <param name="val">The value of the variable</param>
    public void Set(string key, string val){
      var index = keys.IndexOf(key);
      if (index != -1) {
        vals[index] = val;
        return;
      }

      keys.Add(key);
      vals.Add(val);
      comments.Add(System.String.Empty);
    }

    /// <summary>
    /// Set the variable and value if they dont exist including a comment. Updates the variables value and comment if does exist.
    /// </summary>
    /// <param name="key">The variable name</param>
    /// <param name="val">The value of the variable</param>
    /// <param name="comment">The comment of the variable</param>
    public void Set(string key, string val, string comment){
      var index = keys.IndexOf(key);
      if (index != -1) {
        vals[index] = val;
        comments[index] = comment;
        return;
      }

      keys.Add(key);
      vals.Add(val);
      comments.Add(comment);
    }

    /// <summary>
    /// Returns the value for the input variable.
    /// </summary>
    /// <param name="key">The variable name.</param>
    public string Get(string key){
      for(int i = 0; i < keys.Count; i++){
        if(keys[i].Equals(key)){
          return vals[i].ToString();
        }
      }
      return System.String.Empty;
    }

    /// <summary>
    /// Returns the Key, Value and comment of the choosen variable.
    /// </summary>
    /// <returns>String array containing the 3 values</returns>
    /// <param name="key">The variable name.</param>
    public string[] GetLine(string key){
      string[] list = new string[2];

      for(int i = 0; i < keys.Count; i++){
        if(keys[i].Equals(key)){
          list[0] = keys[i].ToString();
          list[1] = vals[i].ToString();
          list[2] = comments[i].ToString();
          return list;
        }
      }

      return list;
    }

    /// <summary>
    /// Removes the selected Variable including its value and comment.
    /// </summary>
    /// <param name="key">The variable name.</param>
    public void Remove(string key){
      var index = keys.IndexOf(key);
      if (index != -1){
          keys.RemoveAt(index);
          vals.RemoveAt(index);
          comments.RemoveAt(index);
          return;
      }
      Debug.LogWarning("Key not found");
    }

    /// <summary>
    /// Save the specified file.
    /// </summary>
    /// <param name="file">The file name.</param>
    public void Save(string file){
      StreamWriter wr = new StreamWriter(GetFullPath(file));

      for(int i = 0; i < keys.Count; i++){
        if(comments[i].Equals(System.String.Empty)){
          wr.WriteLine(keys[i] +"="+ vals[i]);
        } else {
          wr.WriteLine(keys[i] +"="+ vals[i]+" //"+comments[i]);
        }
      }

      wr.Close();

      //Debug.Log(GetFullPath(file) + " Saved");
    }

    /// <summary>
    /// Load the specified file.
    /// </summary>
    /// <param name="file">The file name.</param>
    public void Load(string file){
      keys = new ArrayList();
      vals = new ArrayList();
      comments = new ArrayList();

      string line = System.String.Empty, dir = GetFullPath(file);
      int offset = 0, comment = 0;

      try{
        using(StreamReader sr = new StreamReader(dir)){
          while((line = sr.ReadLine()) != null){
            offset = line.IndexOf("=");
            comment = line.IndexOf("//");
            if(offset > 0){
              if(comment != -1){
                Set(line.Substring(0,offset),line.Substring(offset+1,(comment - (offset+1))),line.Substring(comment+1));
              } else {
                Set(line.Substring(0,offset),line.Substring(offset+1));
              }
            }
          }
          sr.Close();
          //Debug.Log(file + ".ini Loaded");
        }
      } catch(IOException e){
        Debug.Log("Error opening " + GetFullPath(file));
                          Debug.LogWarning(e);
      }
    }

    /// <summary>
    /// How many keys are stored.
    /// </summary>
    public int Count(){
      return keys.Count;
    }
  }
}