Home > Software design >  How to avoid if-else statements, when choosing drives in combobox?
How to avoid if-else statements, when choosing drives in combobox?

Time:01-31

I'm trying to get rid of if-else statements in my function, so I don't need to specify every drive possible. In this case I'm reading a .csv file. Is there any way to avoid the struggle of if-else.

Thanks in advance!

My code now:

if (str == "(D:)")
{
    csvPath = @"D:\file1.CSV";

    try
    {
        using (var fs = File.Open(csvPot, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            var csvFileDescription = new CsvFileDescription
            {
                FirstLineHasColumnNames = true,
                IgnoreUnknownColumns = true,
                SeparatorChar = ',',
                UseFieldIndexForReadingData = false
            };

            var csvContext = new LINQtoCSV.CsvContext();
            var settings = csvContext.Read<Settings>(csvPot, csvFileDescription);

            foreach (var setting in settings)
            {
                tbx_ssid.Text = setting.SSID;
                tbx_pass.Text = setting.password;
            }

            if (tbx_ssid.Text == "" && tbx_pass.Text == "")
            {
                MessageBox.Show("No data!");
            }
        }
    }
    catch (FileNotFoundException)
    {
        MessageBox.Show("File not exsists!");
    }
}
else if (str == "(E:)")
{
.
.
.

CodePudding user response:

You could prepare a Dictionary<string, string> where the key is the drive to use and the value is the filepath to retrieve the file.

Something like this.

Dictionary<string, string> fileToUse = new Dictionary<string, string>();
fileToUse.Add("(D:)", @"D:\file1.CSV");
fileToUse.Add("(E:)", @"E:\someotherfolder\file1.CSV");

Now it is simply a matter of

if (fileToUse.TryGetValue(str, out string file))
{
    // Code that uses _file_
    
}

Another approach is to strip from the str string the opening and closing parenthesys and use the string cleared for a substitution of the first two characters of the filepath

string noPar = str.Trim('(', ')');
string baseFile = @"\file1.CSV";
string fullFile = $"{noPar}{baseFile}";

With this approach however you are forced to have that file in the root folder of the drive choosen (or in some fixed location). Not always the best choice in the long term.

CodePudding user response:

SimonC solved my question. It works for me perfect !

csvPath = $@"{str}/file1.csv";
  • Related