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

            CodeInfo_IniWriteTextLineOp infoOp = cmd.Info.Cast <CodeInfo_IniWriteTextLineOp>();

            string fileName = StringEscaper.Preprocess(s, infoOp.Infos[0].FileName);

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

            bool append = infoOp.Infos[0].Append;

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

            List <IniKey> keyList = new List <IniKey>(infoOp.Infos.Count);

            foreach (CodeInfo_IniWriteTextLine info in infoOp.Infos)
            {
                string sectionName = StringEscaper.Preprocess(s, info.Section);
                string line        = StringEscaper.Preprocess(s, info.Line);

                if (append)
                {
                    keyList.Add(new IniKey(sectionName, line));
                }
                else // prepend
                {
                    keyList.Insert(0, new IniKey(sectionName, line));
                }
            }
            IniKey[] keys = keyList.ToArray();

            string dirPath = Path.GetDirectoryName(fileName);

            if (dirPath == null)
            {
                throw new InternalException("Internal Logic Error at IniWriteTextLineOp");
            }
            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 = IniReadWriter.WriteRawLines(fileName, keyList, append);

            if (result)
            {
                for (int i = 0; i < keys.Length; i++)
                {
                    IniKey kv = keyList[i];
                    logs.Add(new LogInfo(LogState.Success, $"Line [{kv.Key}] written", infoOp.Cmds[i]));
                }
                logs.Add(new LogInfo(LogState.Success, $"Wrote [{keys.Length}] lines to [{fileName}]", cmd));
            }
            else
            {
                for (int i = 0; i < keys.Length; i++)
                {
                    IniKey kv = keyList[i];
                    logs.Add(new LogInfo(LogState.Error, $"Could not write line [{kv.Key}]", infoOp.Cmds[i]));
                }
                logs.Add(new LogInfo(LogState.Error, $"Could not write [{keys.Length}] lines to [{fileName}]", cmd));
            }

            return(logs);
        }