Question Problem with a .cfg file

Lawh

Member
Joined
Jan 17, 2024
Messages
6
Programming Experience
Beginner
There is a program that uses a .cfg file. The file's name is "mods.cfg". Once you run the program a launcher opens that reads this file, and files listed in this .cfg file will be automatically selected in the launcher. They are also in the order in which they are listed in the .cfg file.

In this file, there is a list of file names, each on their own line. As an example, there is a file named "mod1.mod" and a file named "mod2.mod" in the files of the program. In the "mods.cfg" file, there are two lines:

mod2.mod
mod1.mod

Once the launcher is opened, these two files will be selected, and shown in this order, where "mod2.mod" will be on top of "mod1.mod". If they would swap places in the file, they would swap places as you run the launcher.

Here is an issue I ran into, which I don't understand.

I made a CMD program using Visual Studio 22. The program reads this .cfg file and stores it in a string. It takes the string apart into an array, separating the lines using "\n". It organizes them into alphabetical order, clears the file, and then writes each entry back into the file in that order, and that is it.

The result in the "mods.cfg" are as intended. All file names in the file have been organized into the correct order. Here is where the problem begins.

As I open the launcher, no files are selected. The ones in the list are not selected, nor are the ones not on the list.

- If I cut the list out of the file, then save it, then open the launcher, close the launcher, then paste it, and then open the launcher again, nothing is selected.
- If I cut everything out of the file, save it, launch it, close the launcher, type in a file I know is available, save it, and launch the program, the file I typed in is selected in the launcher.

Clearly something is missing in the file as the CMD program writes onto the file, but I cannot see what it is.
Here is my program. Notice, that if I enter the directory of the file either directly, or using the command "debug", the results are the same. I am pretty sure there is some simple solution to this that I am not familiar with at all. Thank you for any assistance you could give me. I can survive without this program, but I cannot easily live with not knowing what the difference is with two superficially identical files.
C#:
// See [URL='https://aka.ms/new-console-template']C# console app template changes in .NET 6+ - .NET[/URL] for more information

//Console.WriteLine("Hello, World!");

//Check file exists in folder
//Read everything in file
//Separate one line at a time
//Organize in alphabetical order
//Clear original file
//Write the organized list to the file
//Give message that list is organized
//Ready - Test it out

using System;

public class Program
{
                         public static void Main()
    {
        //Variables
        int lineCount;

        bool finished = false;

        string modFileDirectory;
        string modFileContent;
        string[] modFileContentArray;
        string modFileContentSorted;
        //Actual
        while (!finished)
        {
            //Intro text, getting the directory, displaying it
            modFileDirectory = GetModFileDirectory();

            if (File.Exists(modFileDirectory))
            {
                //Get content from file in given directory as a string
                modFileContent = GetModFileContent(modFileDirectory);
                //Splice up the string into an array, separating with \n
                modFileContentArray = modFileContent.Split("\n");
                //Sort the array
                Array.Sort(modFileContentArray);
                //Sorted string

                //Get length of array
                lineCount = modFileContentArray.Length;
                File.WriteAllText(modFileDirectory, ""); // Delete all text in the file so that you get a fresh file to write into
                //For every string in array, write it down into the file
              
                for (int i = 0; i < lineCount; i++)
                {
                    using (StreamWriter sw = File.AppendText(modFileDirectory))
                    {
                        if (modFileContentArray[i] != "")
                        {
                            //sw.WriteLine(modFileContentArray[i]); //Write it into the file and add line afterwards
                            sw.Write(modFileContentArray[i]);
                        }
                        if (i == lineCount)
                        {
                            modFileContentSorted = GetModFileContent(modFileDirectory);
                            Console.WriteLine(modFileContentSorted);
                        }
                    }
                }
               
                Console.WriteLine("Selected mods should now be in alphabetical order.");
                finished = true;
            }
            else if (modFileDirectory == "")
            {
                Console.WriteLine("Entry empty. Try again.\n\n");
            }
            else
            {
                Console.WriteLine("File does not exist. Check your directory path or try fully launching and then exiting Kenshi and try again.\n\n");
            }
        }
    }

    public static string GetModFileDirectory()
    {
        Console.WriteLine("Enter the directory to the Kenshi \'mods.cfg\' or the \'__mods.list\' file");
        Console.WriteLine("File is found in ../Kenshi/data/__mods.list");
        Console.WriteLine("Right click the \'mods.cfg\' file -> Copy as Path -> Paste it here");
        Console.WriteLine("Enter or paste the file location here: ");
        string txt = Console.ReadLine();

        if (txt == "debug")
        {
            txt = "D:\\SteamLibrary\\steamapps\\common\\Kenshi\\data\\mods.cfg";
        }
        else if (txt == "debug2")
        {
            txt = "D:\\SteamLibrary\\steamapps\\common\\Kenshi\\data\\__mods.list";
        }
        else
        {
            txt = txt.Replace("\"", string.Empty); //replace " with Empty
        }
        Console.WriteLine($"\nDirectory selected: {txt}" + "\n"); //Display the directory
        return txt;
    }

    public static string GetModFileContent(string modFileDirectory)
    {
        string txt = File.ReadAllText(modFileDirectory);
       
        Console.WriteLine(txt);
        return txt;
    }
}

EDIT:
When I changed program to write a string directly onto the file, it works. I am testing out different ways of doing this, since the program is far from optimized or sensible when it comes to code.
 
Last edited:
Moving to C# General instead of VS.NET general since this isn't a Visual Studio issue, but rather a programming issue.
 
The first question is: Does does the launcher expect the line to be carriage return (CR) delimited, line feed (LF) delimited, or carriage return-line feed (CRLF) delimited?

I'm assuming the code you have above is running on Windows due to the path you have on lines 91 and 95. If so, on Windows the StreamWriter will write files out as as CRLF delimited if you are using WriteLine().

But it looks like your code line 40 is splitting the input by LF, and then just writing out the strings directly without delimiters on line 57. (You have line 56 which uses WriteLine() commented out.) So if the file was originally CRLF delimited, then you are saving the file back out as CR delimited.

None of this will be obvious in your attempts to debug by using Console.WriteLine() to dump the file contents because the original Windows console by default will output strings all the same way regardless if they are CR, LF, or CRLF delimited. (I think there is a way to change console settings to not make this the default, but as I recall it is not commonly done. Also this may change long term as the new Windows Terminal code gains more acceptance.)

In general, only old Macs (and some older systems) use CR delimited text files. Windows has always been CRLF delimited. *nix has always been LF delimited, and modern Macs have become LF delimited as well as a result to their conversion to using a Unix based code base.

Instead of doing your splitting and then rewriting the file one line at a time, I suggest using ReadAllLines() to get an array of lines, and WriteAllLines() to write back the sorted array of lines.
 
The first question is: Does does the launcher expect the line to be carriage return (CR) delimited, line feed (LF) delimited, or carriage return-line feed (CRLF) delimited?

I'm assuming the code you have above is running on Windows due to the path you have on lines 91 and 95. If so, on Windows the StreamWriter will write files out as as CRLF delimited if you are using WriteLine().

But it looks like your code line 40 is splitting the input by LF, and then just writing out the strings directly without delimiters on line 57. (You have line 56 which uses WriteLine() commented out.) So if the file was originally CRLF delimited, then you are saving the file back out as CR delimited.

None of this will be obvious in your attempts to debug by using Console.WriteLine() to dump the file contents because the original Windows console by default will output strings all the same way regardless if they are CR, LF, or CRLF delimited. (I think there is a way to change console settings to not make this the default, but as I recall it is not commonly done. Also this may change long term as the new Windows Terminal code gains more acceptance.)

In general, only old Macs (and some older systems) use CR delimited text files. Windows has always been CRLF delimited. *nix has always been LF delimited, and modern Macs have become LF delimited as well as a result to their conversion to using a Unix based code base.

Instead of doing your splitting and then rewriting the file one line at a time, I suggest using ReadAllLines() to get an array of lines, and WriteAllLines() to write back the sorted array of lines.

I rewrote the writing part of it as I had a chance to look at it while I was a little stuck. The program now works, though the it is very static and unfinished. Functionality will suffice for now since it's getting late. I will make things more legible and uniform, as well as add different settings later for a more dynamic experience.

What you said was unfamiliar to me, so I will spend a while reading up on what you said. This is always good, since I love to learn more. This issue was something I was not expecting to run into at all, and I sort of came to the conclusion which you stated, though had no words to describe it. Here is the working version, and it is good that I sort of bumped into what I suppose is a relatively rare issue, at least in very basic coding.
C#:
// See https://aka.ms/new-console-template for more information

//Console.WriteLine("Hello, World!");

//Check file exists in folder
//Read everything in file
//Separate one line at a time
//Organize in alphabetical order
//Clear original file
//Write the organized list to the file
//Give message that list is organized
//Ready - Test it out

using System;
using System.Runtime.CompilerServices;
using static System.Net.Mime.MediaTypeNames;

public class Program
{
    public static void Main()
    {
        //Variables
        int lineCount;
        bool finished = false;
        bool resetToDefault = false;
        string modFileDirectory;
        string modFileContent;
        string[] modFileContentArray;
        string modFileContentSorted;
        string modSuffix = ".mod";
        string defaultPathBackup = "E:\\BACKUPS\\Kenshi\\kenshiUsedMods.txt";
        string defaultPathModFile = "D:\\SteamLibrary\\steamapps\\common\\Kenshi\\data\\mods.cfg";
        string rerun = "";

        //Actual
        while (!finished)
        {
            //Intro text, getting the directory, displaying it
            modFileDirectory = GetModFileDirectory();

            if (modFileDirectory == "default")
            {
                modFileContent = GetModFileContent(defaultPathBackup, modSuffix);//Get content from file in given directory as a string
                File.WriteAllText(defaultPathModFile, modFileContent);//Write string into the file
                rerun = Console.ReadLine();
                if (rerun != "y")
                {
                    finished = true;//End the while loop by cutting it off
                }
            }
            else
            {
                if (File.Exists(modFileDirectory))
                {
                    modFileContent = GetModFileContent(modFileDirectory, modSuffix);//Get content from file in given directory as a string
                    if (modFileContent == "ERROR")
                    {
                        Console.WriteLine("You need to select some mods in the Kenshi Launcher and hit Save Config. There are no mods selected.");//Display finishing message
                    }
                    else
                    {
                        modFileContentArray = modFileContent.Split("\n");//Splice up the string into an array, separating with \n
                        Array.Sort(modFileContentArray);//Sort the array
                        lineCount = modFileContentArray.Length;//Get length of array
                        modFileContentSorted = BuildStringFromArray(lineCount, modFileContentArray, modFileDirectory);//Get sorted string
                        File.WriteAllText(modFileDirectory, modFileContentSorted);//Write string into the file
                        Console.WriteLine(modFileContentSorted + "\n");//Debug the contents
                        Console.WriteLine("Selected mods should now be in alphabetical order.\n\n");//Display finishing message
                        Console.WriteLine("Run again? y for rerun");//Display rerun info
                        rerun = Console.ReadLine();
                        if (rerun != "y")
                        {
                            finished = true;//End the while loop by cutting it off
                        }
                    }
                }
                else if (modFileDirectory == "")
                {
                    Console.WriteLine("Entry empty. Try again.\n\n");
                }
                else
                {
                    Console.WriteLine("File does not exist. Check your directory path or try fully launching and then exiting Kenshi and try again.\n\n");
                }
            }
        }
    }

    public static string BuildStringFromArray(int lineCount, string[] modFileContentArray, string modFileDirectory)
    {
        string txtSuccess = "No mods in selected list to build upon";
        string txtFailure = "Failed to build string from array";
        for (int i = 0; i < lineCount; i++)
        {
            if (i == 0)
            {
                txtSuccess = modFileContentArray[0] + "\n";
            }
            else
            {
                txtSuccess += modFileContentArray[i] + "\n";
                Console.WriteLine(txtSuccess);
            }
            if (i == lineCount - 1)
            {
                return txtSuccess;
            }
        }
        if (txtSuccess == "No mods in selected list to build upon")
        {
            txtFailure = "Error with building string from array";
            return txtFailure;
        }
        else
        {
            return txtFailure;
        }
    }

    public static string GetModFileDirectory()
    {
        Console.WriteLine("Enter the directory to the Kenshi \'mods.cfg\' or the \'__mods.list\' file");
        Console.WriteLine("File is found in ../Kenshi/data/__mods.list");
        Console.WriteLine("Right click the \'mods.cfg\' file -> Copy as Path -> Paste it here");
        Console.WriteLine("Enter or paste the file location here: ");
        string txt = Console.ReadLine();

        if (txt == "debug")
        {
            txt = "D:\\SteamLibrary\\steamapps\\common\\Kenshi\\data\\mods.cfg";
        }
        else if (txt == "debug2")
        {
            txt = "D:\\SteamLibrary\\steamapps\\common\\Kenshi\\data\\__mods.list";
        }
        else if ((txt == "get list") || (txt == "default"))
        {
            txt = "default";
        }
        else
        {
            txt = txt.Replace("\"", string.Empty); //replace " with Empty
        }
        Console.WriteLine($"\nDirectory selected: {txt}" + "\n"); //Display the directory
        return txt;
    }
    public static string GetModFileContent(string modFileDirectory, string modSuffix)
    {
        string txt = File.ReadAllText(modFileDirectory);
        
        Console.WriteLine(txt);
        if (txt.Contains(modSuffix))
        {
            return txt;
        }
        else
        {
            return "ERROR";
        }
    }
}
 
It's actually a common issue that beginning DOS and Windows programmers run into when they are learning from books and magazine articles written by folks who assume their audience is writing for Unix systems. It was even worse for old time Mac programmers who were learning on the learning curve because their delimiters were carriage returns but all the books and magazine articles would show code using line feeds.
 
Instead of the loop in BuildStringFromArray you can use String.Join method:
C#:
var content = string.Join("\n", modFileContentArray);

When using StreamWriter there is a NewLine property that can be set to customize line terminator.
 
The following is untested code. I'm just doodling at the keyboard while waiting for something. Here's a first pass of how I would write things:
C#:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;

public class Program
{
    public static void Main()
    {
        bool quit = false;
        do
        {
            switch (ShowMenu())
            {
                case Choice.ResetDefaultMods:
                    ResetDefaultMods();
                    break;

                case Choice.SortExistingMods:
                    SortExistingMods();
                    break;

                case Choice.Quit:
                    quit = true;
                    break;
            }
        } while (!quit);
    }

    enum Choice
    {
        ResetDefaultMods = 1,
        SortExistingMods,
        Quit,
    }

    static Choice ShowMenu()
    {
        while (true)
        {
            Console.WriteLine("Main menu:");
            Console.WriteLine("1 - Reset default mods");
            Console.WriteLine("2 - Sort existing mods");
            Console.WriteLine("3 - Quit");
            Console.WriteLine();
            Console.Write("What do you want to do? [1, 2 ,3]: ");

            var input = Console.ReadLine();
            if (!int.TryParse(input, out int value) || value < 1 || value > 3)
                Console.WriteLine("Please enter a value from 1 to 3.");
            else
                return (Choice)(value);
        }
    }

    static void ResetDefaultMods()
    {
        Console.WriteLine("Resetting mods back to the defaults");
        File.Copy(sourceFileName: @"E:\BACKUPS\Kenshi\kenshiUsedMods.txt",
                  destFileName: @"D:\SteamLibrary\steamapps\common\Kenshi\data\mods.cfg",
                  overwrite: true);
    }

    static string RemoveDoubleQuotes(string input)
        => input.Replace("\"", string.Empty);

    static bool IsValidModFile(string filename)
    {
        return File.ReadLines(filename)
                   .Any(line => line.Contains(".mod"));
    }

    static string ReplaceMagicStrings(string input)
    {
        switch (input.ToLower())
        {
            case "debug":
                return @"D:\SteamLibrary\steamapps\common\Kenshi\data\mods.cfg";

            case "debug2":
                return @"D:\SteamLibrary\steamapps\common\Kenshi\data\__mods.list";
        }

        return input;
    }

    static string GetModFileName()
    {
        do
        {
            Console.WriteLine("Enter the directory to the Kenshi 'mods.cfg' or the '__mods.list' file");
            Console.WriteLine("File is found in ../Kenshi/data/__mods.list");
            Console.WriteLine("Right click the 'mods.cfg' file -> Copy as Path -> Paste it here");
            Console.Write("Enter or paste the file location here: ");

            var filename = Console.ReadLine();
            if (string.IsNullOrWhiteSpace(filename))
            {
                Console.WriteLine("Entry empty. Try again.");
                Console.WriteLine();
                Console.WriteLine();
            }
            else
            {
                filename = RemoveDoubleQuotes(filename);
                filename = ReplaceMagicStrings(filename);

                if (!File.Exists(filename))
                {
                    Console.WriteLine("File does not exist. Check your directory path or try fully launching and then exiting Kenshi and try again.");
                    Console.WriteLine();
                    Console.WriteLine();
                }
                else if (!IsValidModFile(filename))
                {
                    Console.WriteLine("You need to select some mods in the Kenshi Launcher and hit Save Config. There are no mods selected.");
                    Console.WriteLine();
                    Console.WriteLine();
                }
                else
                {
                    Console.WriteLine();
                    Console.WriteLine($"Mod file selected: {filename}");
                    Console.WriteLine();
                    return filename;
                }
            }
        } while (true);
    }

    static void DumpLines(string title, IEnumerable<string> lines)
    {
        Console.WriteLine($"{title}:");
        foreach (var line in lines)
            Console.WriteLine(line);
        Console.WriteLine("<<< END >>>");
        Console.WriteLine();
    }

    static void SortExistingMods()
    {
        var filename = GetModFileName();
        var lines = File.ReadAllLines(filename);
        DumpLines($"Original contents of {filename}", lines);

        var sortedLines = lines.Order().ToList();
        DumpLines($"Writing out sorted lines to {filename}", sortedLines);
        File.WriteAllLines(filename, sortedLines);
    }
}
 
I didn't get a chance to really sort things out and simplify things, but I feel like this does what it needs to do well and I will revisit this once I can figure out another project to do and understand more.

Thanks everybody!

I couldn't reply earlier since I didn't have my password for this forum on my phone. I will have a look look at the code, and thanks for all the intel. Really helps to learn when you understand rather than try to remember things. Here is what I came up with:

C#:
using System;
using System.IO;
using System.Reflection;
using System.Reflection.Metadata;
using System.Runtime.CompilerServices;
using System.Xml.Serialization;
using static System.Net.Mime.MediaTypeNames;
static class Program
{
    static void Main()
    {
        string installPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + "\\";
        string settingsFile = "settings.cfg";
        string backupFile = "backup.cfg";
        string modFile = "mods.cfg";
        string defaultPathSettings = installPath + settingsFile;
        string defaultPathBackup = installPath + backupFile;
        //Variables
        bool finished = false;
        string[] configArray;
        string[] settingsLines = new string[1];
        string settingLineEmpty = "";
        string configData = "";
        string config = "";
        string backup = "";
        string restore = "(1) \"restore\"";
        string organize = "(2) \"organize\"";
        string resetSettings = "(3) \"reset settings\"";
        string resetBackup = "(4) \"reset backup\"";
        string resetAll = "(5) \"reset all\"";
        string createBackup = "(6) \"create backup\"";

        string quitProgram = "(0) \"quit\"";
        string commandRequest = "";
        string defaultPathConfig;
        string modSuffix = ".mod";
        //string defaultBackupMe = "E:\\BACKUPS\\Kenshi\\kenshiUsedMods.txt";
        //string defaultModFileMe = "D:\\SteamLibrary\\steamapps\\common\\Kenshi\\data\\mods.cfg";
        string error = "error";

        ///Intro
        Message("THIS MOD SHOULD BE DOWNLOADED ONLY FROM STEAM WORKSHOP");
        Message("IF THIS FILE IS FOUND ANYWHERE ELSE EXCEPT IN THE CREATOR'S WORKSHOP,");
        Message("DO NOT DOWNLOAD");
        Message("");
        Message("CREATED BY LAWH");
        Message("");

        //Actual
        while (!finished)
        {
            //Check if settings file exists, if not create it
            if (!File.Exists(defaultPathSettings))
            {
                settingsLines[0] = settingLineEmpty;
                File.WriteAllLines(defaultPathSettings, settingsLines);
                Message("Creating Settings File..");
                Message("You can find a file named " + settingsFile + " in the directory of this app.");
                Message("");
            }
            //Read default paths from the settings files
            settingsLines = File.ReadAllLines(defaultPathSettings);
            //If Kenshi mods.cfg path empty, get path through input
            if (settingsLines[0] == settingLineEmpty)
            {
                settingsLines[0] = GetDefaultPathConfig(modFile);
                if (settingsLines[0] == error)
                {
                    Message("Path to " + modFile + " failed.");
                    Message("");
                }
                else
                {
                    File.WriteAllLines(defaultPathSettings, settingsLines);
                }
            }
            else //Proceed
            {
                //if error, end
                if (settingsLines[0] == error)
                {
                    Message("Path to file does not exist. Restarting.");
                    Message("");
                }
                else
                {
                    //Change variable names
                    defaultPathConfig = settingsLines[0];
                    //If no backup file, create it
                    if (!File.Exists(defaultPathBackup))
                    {
                        configData = File.ReadAllText(defaultPathConfig);
                        File.WriteAllText(defaultPathBackup, configData);
                        Message("Creating Backup file..");
                        Message("You can find a file named " + backupFile + " in the directory of this app.");
                        Message("");
                    }

                    //Ask what to do next
                    commandRequest = GetCommandRequest(restore, organize, resetSettings, resetBackup, resetAll, createBackup, quitProgram);
                    if (commandRequest == error)
                    {
                        Message("Your command is not recognized. Try again.");
                        Message("");
                    }
                    else if (commandRequest == "restore")//Proceed with Restore
                    {
                        //Write All onto Config File
                        if (defaultPathConfig != settingLineEmpty)
                        {
                            //Read All from Backup File and Write it in the Config file
                            backup = File.ReadAllText(defaultPathBackup);
                            File.WriteAllText(defaultPathConfig, backup);
                            Message("Your " + modFile + " has been restored from you backup file."); //End
                            Message("");
                        }
                        else
                        {
                            Message("The default path to the config file is still empty."); //End
                            Message("");
                        }

                    }
                    else if (commandRequest == "organize")//Proceed with Organization
                    {
                        //Read all from Backup File
                        configArray = File.ReadAllLines(defaultPathConfig);
                        //If list is empty, End
                        if (!configArray[0].Contains(modSuffix))
                        {
                            Message("There are no mods to sort in your mod list. Add some mods using the Kenshi launcher to organize them.");
                            Message("");
                        }
                        else //Proceed
                        {
                            Array.Sort(configArray);//Sort the array
                            File.WriteAllLines(defaultPathConfig, configArray);
                            config = File.ReadAllText(defaultPathConfig);
                            Message(config);
                            Message("Your mod list should now be in alphabetical order.");//End
                            Message("");
                        }
                    }
                    else if (commandRequest == "reset settings")//Proceed with Organization
                    {
                        if (File.Exists(defaultPathSettings))
                        {
                            File.Delete(defaultPathSettings);
                        }
                        Message("Your settings file has been deleted.");
                        Message("");
                    }
                    else if (commandRequest == "reset backup")//Proceed with Organization
                    {
                        if (File.Exists(defaultPathBackup))
                        {
                            File.Delete(defaultPathBackup);
                        }
                        Message("Your backup file has been deleted.");
                        Message("");
                    }
                    else if (commandRequest == "reset all")//Proceed with Organization
                    {
                        if (File.Exists(defaultPathBackup))
                        {
                            File.Delete(defaultPathBackup);
                        }
                        if (File.Exists(defaultPathSettings))
                        {
                            File.Delete(defaultPathSettings);
                        }
                        Message("Your backup and settings file has been deleted.");
                        Message("");
                    }
                    else if (commandRequest == "create backup")//Proceed with Organization
                    {
                        configData = File.ReadAllText(defaultPathConfig);
                        File.WriteAllText(defaultPathBackup, configData);
                        Message("Creating Backup file..");
                        Message("You can find a file named " + backupFile + " in the directory of this app.");
                        Message("");
                    }
                    else if (commandRequest == "quit")//Proceed with Organization
                    {
                        finished = true;
                    }
                    Message("");
                }
            }

        }
    }
    public static void Message(string message)
    {
        Console.WriteLine(message);
    }
    public static string GetDefaultPathConfig(string modFile)
    {
        Message("Enter the directory to the Kenshi " + modFile + " file");
        Message("File is found in ../Kenshi/data/" + modFile);
        Message("Drag and drop the file into this window and proceed");
        Message("or");
        Message("Right click the \'mods.cfg\' file -> Copy as Path -> Paste it here: ");
        string? txt = Console.ReadLine();
        Message("");
        txt = txt.Replace("\"", string.Empty);
        if (File.Exists(txt))
        {
            return txt;
        }
        else
        {
            return "error";
        }
    }
    public static string GetCommandRequest(string restore, string organize, string resetSettings, string resetBackup, string resetAll, string createBackup, string quitProgram)
    {
        Message("Would you like to:");
        Message(restore + " your mod list from the backup?");
        Message(organize + " your selected mods in an alphabetical order?");
        Message(resetSettings + " and delete the settings file?");
        Message(resetBackup + " and delete the backup file?");
        Message(resetAll + " and delete the settings and backup files?");
        Message(createBackup + " and store your current mod list in the backup file?");
        Message("");
        Message(quitProgram + "and close this window?");
        Message("");
        Message("Resetting can help with errors");
        Message("Please type either the number or keyword below to make your choice: ");
        string? txt = Console.ReadLine();
        Message("");
        if ((txt == "1") || (txt == "restore"))
        {
            txt = "restore";
            return txt;
        }
        else if ((txt == "2") || (txt == "organize"))
        {
            txt = "organize";
            return txt;
        }
        else if ((txt == "3") || (txt == "reset settings"))
        {
            txt = "reset settings";
            return txt;
        }
        else if ((txt == "4") || (txt == "reset backup"))
        {
            txt = "reset backup";
            return txt;
        }
        else if ((txt == "5") || (txt == "reset all"))
        {
            txt = "reset all";
            return txt;
        }
        else if ((txt == "6") || (txt == "create backup"))
        {
            txt = "create backup";
            return txt;
        }
        else if ((txt == "0") || (txt == "quit"))
        {
            txt = "quit";
            return txt;
        }
        else
        {
            return "error";
        }
    }
}
 
Last edited:
C# is an object oriented language that highly recommends being strongly typed. You're setting of settingsLines[0] to an error message or empty string goes against this principle. It's what some people call being "stringly-typed". (You've probably seen that practice of passing around information in strings from JavaScript.)
 
C#:
configData = File.ReadAllText(defaultPathConfig);
File.WriteAllText(defaultPathBackup, configData);
could be simplified to be just:
C#:
File.Copy(defaultPathConfig, defaultPathBackup, overwrite: true);

Why waste I/O bandwidth, CPU cycles and memory reading in the contents into memory, just to turnaround and write the data into another file?
 
else if ((txt == "6") || (txt == "create backup")) { txt = "create backup"; return txt; }

This (and others like it) could just be if(txt == "6"). Can you figure out why?

You can put multi line strings into c# code with @""
C#:
Message(@"This
is
a
multi
line
string")

But don't indent them, otherwise the indentation will print out. Having your string in separate variables(in a separate file) with good names will help tidy up and compact your code
 
Last edited:
I didn't know the C language before this, and this was my first C program ever, written in a single day, so that is the "why" to a lot of the choices. Thanks for the information, I'll have a look at it once I get around to it!
 
Just so you don't confuse other devs, we generally call it C# - C is also a language, but not this one ;)
 

Latest posts

Back
Top Bottom