Avatar of PeterBaileyUk
PeterBaileyUk
 asked on

File naming function in c#

I would like to make a function that takes two strings passed to it and renames it and passes that new name back.
the input strings it will get will be

parameter 1 in "region 1" or "region 2" or "region 3"
parameter 2 in "originalfilename" an ex: "UNArpC1C6A03"

in the filename the c1c6 is constant but text to left and right of that will change

if
 "region 1" then output becomes "UNArpC1C2A03"
 "region 2" then output becomes "UNArpC3C4A03"
 "region 3" then output becomes "UNArpC5C6A03"

end


so another example I pass
"Region 1" and original filename "UNLeadC1C6A101"

will output "UNLeadC1C2A101

"region 2", "UNLeadC1C6A101"
will output "UNLeadC3C4A101"

"region 3", "UNLeadC1C6A101"

will output "UNLeadC5C6A101"

I dont know C# so dont know how to start this
C#VBA

Avatar of undefined
Last Comment
Fernando Soto

8/22/2022 - Mon
SOLUTION
Ryan Chong

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
PeterBaileyUk

ASKER
I am thinking how I can tailor for :
in the filename the c1c6 is constant but text to left and right of that will change

in vba

I would use an instr to find the start position of c1c6 which would then allow me to work out what the characters were upto c1 ie c1c6 -1 and also after c6 as those will change in length whereas here I believe they are fixed

does c# substring allow me to do that?
PeterBaileyUk

ASKER
0 to substring position -1 = first part of string
substring position + 5 to len(n2) i believe is the last part.

c1c6 always remains 4 characters.
PeterBaileyUk

ASKER
I think this will do it although not sure how to test it yet.
static String getFileName(String n1, String n2)
{
    try {


        String v = "";

      int16 SubstringPosition=0;
      int16 StrLen=n2.len;

         switch (n1.ToLower()) {
         case "region 1":
         default:
            v = n2.Substring(0,SubstringPosition-1) + "C1C2" + n2.Substring(SubstringPosition+5,StrLen);
            break;
         case "region 2":
            v = n2.Substring(0,SubstringPosition-1) + "C3C4" + n2.Substring(SubstringPosition+5,StrLen);
            break;
         case "region 3":
            v = n2.Substring(0,SubstringPosition-1) + "C5C6" + n2.Substring(SubstringPosition+5,StrLen);
            break;
         }
         return v;
    } catch (Exception e) {
        return "";
    }
}
Console.WriteLine("test 1 = "+getFileName("region 1","UNArpC1C6A03"));
Console.WriteLine("test 2 = "+getFileName("region 2","UNArpC1C6A03"));
Console.WriteLine("test 3 = "+getFileName("region 3","UNArpC1C6A03"));
Console.WriteLine("test 4 = "+getFileName("region 4","test"));

   

position begin IndexOf(N2)
This is the best money I have ever spent. I cannot not tell you how many times these folks have saved my bacon. I learn so much from the contributors.
rwheeler23
PeterBaileyUk

ASKER
ive since installed visual studio but think its missing stuff as I cannot test the function as i get cs0246 errors.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;


namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("test 1 = " + getFileName("region 1", "UNArpC1C6A03"));
        }





        static String getFileName(String n1, String n2)
        {
            try
            {


                String v = "";

                int16 SubstringPosition = 0;
                int16 StrLen = n2.len;

                switch (n1.ToLower())
                {
                    case "region 1":
                    default:
                        v = n2.Substring(0, SubstringPosition - 1) + "C1C2" + n2.Substring(SubstringPosition + 5, StrLen);
                        break;
                    case "region 2":
                        v = n2.Substring(0, SubstringPosition - 1) + "C3C4" + n2.Substring(SubstringPosition + 5, StrLen);
                        break;
                    case "region 3":
                        v = n2.Substring(0, SubstringPosition - 1) + "C5C6" + n2.Substring(SubstringPosition + 5, StrLen);
                        break;
                }
                return v;
            }
            catch (Exception e)
            {
                return "";
            }
        }


    }
}

Open in new window


I am sure the code is ok now.
SOLUTION
Fernando Soto

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
PeterBaileyUk

ASKER
You used regex nice, I have no experience of c# so was where i was, this is neat as i see it replaces the middle section.

I will try run it, visual studio is strange to me.
PeterBaileyUk

ASKER
i assume you have no objection to sharing the points with the previous poster?
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
PeterBaileyUk

ASKER
do i need to add some reference to my main for this to work?

it will actually be put into this:

using System;
using System.IO;
using System.Windows.Forms;
using System.Collections.Generic;
using SoundForge;

// Adds regions every 16 seconds to an open audio file. 
// Exports every odd region to a user supplied output directory in the same format as the original open audio file.

public class EntryPoint
{
    public void Begin(IScriptableApp app)
    {
        // select the output directory for the exported regions
        string outDirectory = SfHelpers.ChooseDirectory("Choose the output directory.", @"C:\");

        ISfFileHost work_file = app.CurrentFile;

        // File extension for naming the ouput files
        string outExt = work_file.SaveFormat.Extension;

        // undo wrapper for this script.
        int scriptUndo = work_file.BeginUndo("ScriptUndo");

        SfAudioSelection asel = new SfAudioSelection(work_file);
        SfAudioMarkerList mark_list = work_file.Markers;
        // clear any existing regions
        mark_list.Clear();

        long file_length = asel.Length;
        double lengthLeft = work_file.Formatter.PositionToTime(file_length);
        long regionLength = work_file.Formatter.TimeToPosition(16);
        long currentPos = work_file.Formatter.TimeToPosition(0);

        bool keepGoing = true;
        int regionCount = 1;
        while(keepGoing){
            // check to see if there is enough length left to add the next region
            if (lengthLeft > 8.0)
            {
                string regionName = String.Format("Region_{0}", regionCount);

                // add region
                mark_list.AddRegion(currentPos, regionLength, regionName);

                // export to file if this is an export region
                if (regionCount % 2 != 0)
                {
                    SfAudioSelection regionSel = new SfAudioSelection(currentPos, regionLength);
                    string saveName = Path.Combine(outDirectory, String.Format("{0}.{1}", regionName, outExt));
                    exportRegionToFile(saveName, work_file, regionSel, app);  
                }

                // update our tracking vars.
                currentPos += regionLength;
                lengthLeft -= 8.0;
                regionCount++;

            }
            // else make a region out of whatever time is leftover and set keepGoing to False
            else{
                string regionName = String.Format("Region_{0}", regionCount);
                regionLength = work_file.Formatter.TimeToPosition(lengthLeft);
                mark_list.AddRegion(currentPos, regionLength, regionName);
                // export to file if this is an export region
                if (regionCount % 2 != 0)
                {
                    SfAudioSelection regionSel = new SfAudioSelection(currentPos, regionLength);
                    string saveName = Path.Combine(outDirectory, String.Format("{0}.{1}", regionName, outExt));
                    exportRegionToFile(saveName, work_file, regionSel, app);
                }

                // stop our loop
                keepGoing = false;
            }
        }

        // close the undo wrapper
        work_file.EndUndo(scriptUndo, false);
    }

	




    public void exportRegionToFile(string regionName, ISfFileHost workFile, SfAudioSelection regionSelection, IScriptableApp app){
        ISfFileHost newFile = app.NewFile(workFile.DataFormat, true);
        newFile.OverwriteAudio(0, 0, workFile, regionSelection);
        newFile.SaveAs(regionName, workFile.SaveFormat.Guid, "Default Template", RenderOptions.WaitForDoneOrCancel);
        newFile.Close(CloseOptions.SaveChanges);
    }

    public void FromSoundForge(IScriptableApp app)
    {
        ForgeApp = app; //execution begins here
        app.SetStatusText(String.Format("Script '{0}' is running.", Script.Name));
        Begin(app);
        app.SetStatusText(String.Format("Script '{0}' is done.", Script.Name));
    }
    public static IScriptableApp ForgeApp = null;
    public static void DPF(string sz) { ForgeApp.OutputText(sz); }
    public static void DPF(string fmt, params object[] args) { ForgeApp.OutputText(String.Format(fmt, args)); }
} //EntryPoint

Open in new window

Fernando Soto

Hi Peter;

Yes the Regex in this case replaces the middle section of the string in the following way. Using this Regex, Regex.Replace(n2, @"C\dC\d", "C1C2");,  the following is how it is executed.

The first parameter is the string that the Regex will operate on.
The second parameter is the Regex pattern that will be applied on the string. Where the following pattern, "C\dC\d", means the following:
    Find the character capital C followed by any digit followed by the character capital C
    followed by any digit. when it is found replace it with the replacement string the
    third parameter.
ASKER CERTIFIED SOLUTION
Fernando Soto

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
PeterBaileyUk

ASKER
a big thank you
Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
Fernando Soto

Not a problem Peter, glad I was able to help.