Beispiel #1
0
        public static List <LogInfo> IniWrite(EngineState s, CodeCommand cmd)
        {
            List <LogInfo> logs = new List <LogInfo>();

            CodeInfo_IniWrite info = cmd.Info.Cast <CodeInfo_IniWrite>();

            string fileName    = StringEscaper.Preprocess(s, info.FileName);
            string sectionName = StringEscaper.Preprocess(s, info.Section);
            string key         = StringEscaper.Preprocess(s, info.Key);
            string value       = StringEscaper.Preprocess(s, info.Value);

            Debug.Assert(fileName != null, $"{nameof(fileName)} != null");
            Debug.Assert(sectionName != null, $"{nameof(sectionName)} != null");
            Debug.Assert(key != null, $"{nameof(key)} != null");
            Debug.Assert(value != null, $"{nameof(value)} != null");

            if (sectionName.Length == 0)
            {
                return(LogInfo.LogErrorMessage(logs, "Section name cannot be empty"));
            }
            if (key.Length == 0)
            {
                return(LogInfo.LogErrorMessage(logs, "Key name cannot be empty"));
            }

            if (!StringEscaper.PathSecurityCheck(fileName, out string errorMsg))
            {
                return(LogInfo.LogErrorMessage(logs, errorMsg));
            }

            string dirPath = Path.GetDirectoryName(fileName);

            if (dirPath == null)
            {
                throw new InternalException("Internal Logic Error at IniWrite");
            }
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
            }

            // If a dest file does not exist, create an empty file to force ANSI encoding as default in IniReadWriter.
            if (!File.Exists(fileName))
            {
                File.Create(fileName).Dispose();
            }

            bool result;

            if (s.CompatAutoCompactIniWriteCommand)
            {
                result = IniReadWriter.WriteCompactKey(fileName, sectionName, key, value);
            }
            else
            {
                result = IniReadWriter.WriteKey(fileName, sectionName, key, value);
            }

            if (result)
            {
                logs.Add(new LogInfo(LogState.Success, $"Key [{key}] and it's value [{value}] written to [{fileName}]", cmd));
            }
            else
            {
                logs.Add(new LogInfo(LogState.Error, $"Could not write key [{key}] and it's value [{value}] to [{fileName}]", cmd));
            }

            return(logs);
        }