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

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

            string fileName = StringEscaper.Preprocess(s, info.FileName);
            string section  = StringEscaper.Preprocess(s, info.Section);
            string line     = StringEscaper.Preprocess(s, info.Line);

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

            if (section.Length == 0)
            {
                return(LogInfo.LogErrorMessage(logs, "Section 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 IniWriteTextLine");
            }
            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.WriteRawLine(fileName, section, line, info.Append);

            if (result)
            {
                logs.Add(new LogInfo(LogState.Success, $"Line [{line}] wrote to [{fileName}]", cmd));
            }
            else
            {
                logs.Add(new LogInfo(LogState.Error, $"Could not write line [{line}] to [{fileName}]", cmd));
            }

            return(logs);
        }