0

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);
        }
    }

2 Answers2

2

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

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
  • Wow, this works a treat thank you. So if I understand correctly... We are gathering the file path and splitting it into parts (Path and Name). Then we are storing the Name string and splitting it into sections determined by the '.'. Now we can change that partition from one name to another and rebuild the name. – Oogle_doogleson May 31 '21 at 04:06
  • Yep! That's it. – ProgrammingLlama May 31 '21 at 05:03
  • Hi Llama, just a quick follow up question if I may. Could I use a similar method to change the actual file name (the bit before .0001.jpg) based on a textbox entry? For example, Apple.0001.jpg takes name from textbox entry (Lets say we type 'Fruit') and combines with the rename -2 to become Fruit.Apple.jpg? – Oogle_doogleson Jun 01 '21 at 04:03
  • 1
    Sure, you could read the whole earlier part, or just some small part of it. If you want to match a lot, you might want to look into regular expressions to divide up the filename more effectively. – ProgrammingLlama Jun 01 '21 at 04:08
  • Hi @Llama Sorry to bug you again, same topic ;( I'm struggling to use this method to rename the prefix to whatever is entered into a Textbox. Any chance you can show me an example based of the above you produced? I would assume that because we are defining the name from a Textbox entry, that the Dictionary would not be needed? But I don't understand how to allow the renaming at index -3 from the Textbox – Oogle_doogleson Jun 02 '21 at 13:47
  • I've Solved it :) – Oogle_doogleson Jun 03 '21 at 06:40
  • @Oogle_doogleson Oh, sorry! I saw your comment last night and intended to get back to you today, but then I had a really hectic morning. I'm glad you managed to get it sorted! – ProgrammingLlama Jun 03 '21 at 06:44
0

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()

Amit Verma
  • 2,450
  • 2
  • 8
  • 21