简体   繁体   中英

Converting from vb.net to c#, switch function not working

So I have been working on a small project (Previously built with vb.net) in C# ( Being honest, I have used an online vb.net to c# converter to get to this point.) that will basically rename the suffix of a set of files to specific predetermined names (hard coded).

Firstly the working part...

Press button_1, a file dialogue opens and you select files. These are then populated into a listbox_1.

Now press button_2 and the files from listbox_1 are renamed and sent to listbox_2.

Now the issue I am having...

For some reason I cannot figure out, the names are not being changed through the switch statement, they are just taking the string variable name and populating listbox_2 with blank entries (Because the starting Variable is empty).

string NewFileName = "";

I'm not sure what is happening here at all so if anyone is able to help me out that would be great.

 private string GetNewName(string OriginalFileName)
    {
        string NewFileName = "";

        switch (true)
        {
            case object _ when OriginalFileName.Contains(".0001"):
                {
                    NewFileName = OriginalFileName.Replace(".0001", "APPLE");
                    break;
                }

            case object _ when OriginalFileName.Contains(".0002"):
                {
                    NewFileName = OriginalFileName.Replace(".0002", "PEAR");
                    break;
                }
        }

        return NewFileName;
    }

private void BTN_ProcessNames_Click(object sender, EventArgs e)
    {
        foreach (Tuple<string, string> t in listbox_1.Items)
        {
           var NewName = GetNewName(t.Item2);
           listbox_2.Items.Add(NewName);
        }
    }

I would create a mapping:

private static readonly IReadOnlyDictionary<string, string> _mapping = new Dictionary<string, string>()
{
    { "0001", "APPLE" },
    { "0002", "PEAR" }
};

And then a method to extract the id, look it up in the mapping, and replace it:

private string GetNewName(string originalFileName)
{
    // if the path is c:\test\Green_.0001.jpg then we'll end up with filePath containing c:\test and fileName containing Green_.0001.jpg
    string filePath = Path.GetDirectoryName(originalFileName);
    string fileName = Path.GetFileName(originalFileName); // get only the name part

    // Split the filename by .
    string[] parts = fileName.Split('.');

    // If we have enough parts in the filename try and extract the id and replace it
    if (parts.Length >= 2)
    {
        // extract the id (e.g. 0001)
        string id = parts[parts.Length - 2];

        // look it up in the mapping dictionary
        if (_mapping.TryGetValue(id, out var newName))
        {
            // join everything up to the id (i.e. Green_)
            string leftPart = string.Join(".", parts.Take(parts.Length - 2));
            // Append the new name and the last part (the extension)
            fileName = $"{leftPart}{newName}.{parts.Last()}";
        }
    }

    // Recombine the filePath and fileName
    return Path.Combine(filePath, fileName);
}

Note that this method will return the original filename if the id isn't in the mapping, or the filename doesn't contain enough . s.

Try it online

Use if else statement. If you want to use switch then check at first and then use the switch.

Use below link for reference.

Use string.Contains() with switch()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM