File naming function in c#

PeterBaileyUk
PeterBaileyUk used Ask the Experts™
on
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
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Ryan ChongSoftware Team Lead
Commented:
you can try customize this:

static String getFileName(String n1, String n2)
{
    try {
        String v = "";
         switch (n1.ToLower()) {
         case "region 1":
         default:
            v = n2.Substring(0,5) + "C1C2" + n2.Substring(9,3);
            break;
         case "region 2":
            v = n2.Substring(0,5) + "C3C4" + n2.Substring(9,3);
            break;
         case "region 3":
            v = n2.Substring(0,5) + "C5C6" + n2.Substring(9,3);
            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"));

Open in new window

Author

Commented:
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?

Author

Commented:
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.
Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

Author

Commented:
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)

Author

Commented:
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.
Fernando SotoRetired
Distinguished Expert 2017
Commented:
Hi Peter;

I rewrote the code so that it works better. Your original code will throw an out of range when accessing the string. Also please read the comment in the catch block.
static String getFileName(String n1, String n2)
{
    try
    {
        String v = "";

        switch (n1.ToLower())
        {
            case "region 1":
            default:
                v = Regex.Replace(n2, @"C\dC\d", "C1C2");
                break;
            case "region 2":
                v = Regex.Replace(n2, @"C\dC\d", "C3C4");
                break;
            case "region 3":
                v = Regex.Replace(n2, @"C\dC\d", "C5C6");
                break;
        }
        return v;
    }
    catch (Exception e)
    {
        // You should never use a try/catch block unless you intend to handle the exception.
        // This will cause the exception to be swollowed up and you will not know why the programe is not working correctly
        return "";
    }
}

Open in new window

Author

Commented:
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.

Author

Commented:
i assume you have no objection to sharing the points with the previous poster?

Author

Commented:
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 SotoRetired
Distinguished Expert 2017

Commented:
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.
Retired
Distinguished Expert 2017
Commented:
Hi Peter;

To your post, "i assume you have no objection to sharing the points with the previous poster?", not a problem.

To your post, "do i need to add some reference to my main for this to work?", You will need the following using statement.

using System.Text;

The code I modified was a function and can be called from any where by using its name and the correct parameters in the correct order.

Author

Commented:
a big thank you
Fernando SotoRetired
Distinguished Expert 2017

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

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial