none
How can i write this text and then increment it by 1? c# RRS feed

  • Question

  • If you would kindly write this code for me i will really appreciate it like a lot !!! In my macro i will just use a button to activate this code so each time it runs it will have to write the path which could be something Documents/test_1.cs then next time i activate the code again it would be Documents/test_2.cs

    Just watch the video and you will understand what i am trying to do ;)

    https://youtu.be/xYuidYmCWS8

    Wednesday, October 3, 2018 6:15 AM

All replies

  • Hello TheUninvited123,

    1. Try the following for a start :

    string IncrementFileName(string strLastFileName)
    {
        string strBasicFileName = "test__";
        int iLastCount = Convert.ToInt32(strLastFileName.Substring(strBasicFileName.Length));
        return string.Format("{0:S}{1:D}", strBasicFileName, ++iLastCount);
    }
    

    2. You can call the above function as follows :

    string strNewFileName = IncrementFileName("test__5");

    3. Hope this helps.

    - Bio.


    Please visit my blog : http://limbioliong.wordpress.com/

    • Proposed as answer by DerChris88 Tuesday, October 9, 2018 6:34 AM
    Wednesday, October 3, 2018 7:12 AM
  • Hello,

    >Just watch the video and you will understand

    It would be much better if you describe what try to achieve and now you try to achieve.

    If the description will be accompanied with code you develop and explanation of what didn't work as expected - there will be a point for reviewing a problem.


    Sincerely, Highly skilled coding monkey.

    Wednesday, October 3, 2018 7:56 AM
  • Hi,

    I would implement a class to do the job:

    public class PathStringBuilder
    {
        private int startValue = 1;
        private string extension = "cs";
        private string rootaPath = "Documents/";
        private string filenameBase = "test_";
    
        public string GetNext()
        {
            return $"{rootaPath}{filenameBase}{startValue++}.{extension}";
        }
    }
    
    public static void Main(string[] args)
    {
        var psb = new PathStringBuilder();
        var str1 = psb.GetNext();
        var str2 = psb.GetNext();
        var str3 = psb.GetNext();
    }

    Greetings, Chris

    • Proposed as answer by DerChris88 Tuesday, October 9, 2018 6:34 AM
    Wednesday, October 3, 2018 9:18 AM
  • Hi,

    here is an update to store the current index in a file:

    public class PathStringBuilder
    {
        private int startValue = 1;
        private string extension = "cs";
        private string rootaPath = "Documents/";
        private string filenameBase = "test_";
    
        private const string NUMBER_FILE = "index.dat";
    
        private int getNumber()
        {
            if (File.Exists(NUMBER_FILE))
                using (var file = File.Open(NUMBER_FILE, FileMode.OpenOrCreate))
                {
                    byte[] numberArray = new byte[4];
                    file.Read(numberArray, 0, 4);
                    int number = BitConverter.ToInt32(numberArray, 0);
                    file.Position = 0;
                    var test = BitConverter.GetBytes(number + 1);
                    file.Write(test, 0, 4);
                    return number;
                }
            else
                File.WriteAllBytes(NUMBER_FILE, BitConverter.GetBytes(startValue + 1));
            return startValue;
        }
    
        public string GetNext()
        {
            return $"{rootaPath}{filenameBase}{getNumber()}.{extension}";
        }
    }
    
    public static void Main(string[] args)
    {
        var psb = new PathStringBuilder();
        var str1 = psb.GetNext();
        var str2 = psb.GetNext();
        var str3 = psb.GetNext();
    }

    Greetings, Chris

    PS: To reset the index you have to delete index.dat
    • Edited by DerChris88 Wednesday, October 3, 2018 9:47 AM
    • Proposed as answer by DerChris88 Tuesday, October 9, 2018 6:34 AM
    Wednesday, October 3, 2018 9:45 AM
  • Hi,

    I would implement a class to do the job:

    public class PathStringBuilder
    {
        private int startValue = 1;
        private string extension = "cs";
        private string rootaPath = "Documents/";
        private string filenameBase = "test_";
    
        public string GetNext()
        {
            return $"{rootaPath}{filenameBase}{startValue++}.{extension}";
        }
    }
    
    public static void Main(string[] args)
    {
        var psb = new PathStringBuilder();
        var str1 = psb.GetNext();
        var str2 = psb.GetNext();
        var str3 = psb.GetNext();
    }

    Greetings, Chris

    first of all thanks for trying to help me out, i really appreciate it!! But i am getting some errors:

    Line 17:Unexpected character $

    Line 4: } expected

    Line 30:type or namespace definition,or end of file expected;

    The macro recorder also requires the c# to have the class program and a void Main like this otherwise it gets errors so is kind of complicated sorry if i ask for too much i just really want to make this work:
    Their default c# script is like this:

    public class Program
    {
    	public static void Main()
    	{
    		System.Windows.Forms.MessageBox.Show("test");
    	}
    }



    My currect c# code:

    public class Program { public static void Main() { public class Programs { public class PathStringBuilder { private int startValue = 1; private string extension = "cs"; private string rootaPath = "Documents/"; private string filenameBase = "test_"; public string GetNext() { return $"{rootaPath}{filenameBase}{startValue++}.{extension}"; } } public static void Main(string[] args) { var psb = new PathStringBuilder(); var str1 = psb.GetNext(); var str2 = psb.GetNext(); var str3 = psb.GetNext(); } } } }





    Wednesday, October 3, 2018 2:16 PM
  • Hi,

    looks like you are using an older version of C#.  Try to use this GetNetxt method:

    public string GetNext()
    {
        return rootaPath + filenameBase + getNumber() + "." + extension;
    }

    You have Main two times. Delete one.

    public class Program { public static void Main() { var psb = new PathStringBuilder();

    //Now call psb.GetNext() to get the next filePath-string { public class PathStringBuilder { private int startValue = 1; private string extension = "cs"; private string rootaPath = "Documents/"; private string filenameBase = "test_"; public string GetNext() { return rootaPath + filenameBase + getNumber() + "." + extension; } } }

    But if you want to get some filePaths, and next time you are starting the programm you want to continue you should use the version with the method getNumber() or it's starting at 1 again.

    Greetings, Chris
    • Edited by DerChris88 Wednesday, October 3, 2018 2:59 PM
    Wednesday, October 3, 2018 2:56 PM
  • okay i try and copy paste your code still errors in the way now it says

    Line 8: } expected

    Wednesday, October 3, 2018 10:27 PM
  •     class Program
        {
            public class PathStringBuilder
            {
                private int startValue = 1;
                private string extension = "cs";
                private string rootaPath = "Documents/";
                private string filenameBase = "test_";
    
                private const string NUMBER_FILE = "index.dat";
    
                private int getNumber()
                {
                    if (File.Exists(NUMBER_FILE))
                        using (var file = File.Open(NUMBER_FILE, FileMode.OpenOrCreate))
                        {
                            byte[] numberArray = new byte[4];
                            file.Read(numberArray, 0, 4);
                            int number = BitConverter.ToInt32(numberArray, 0);
                            file.Position = 0;
                            var test = BitConverter.GetBytes(number + 1);
                            file.Write(test, 0, 4);
                            return number;
                        }
                    else
                        File.WriteAllBytes(NUMBER_FILE, BitConverter.GetBytes(startValue + 1));
                    return startValue;
                }
    
                public string GetNext()
                {
                    return rootaPath + filenameBase + getNumber() + "." + extension;
                }
            }
    
            public static void Main(string[] args)
            {
                var psb = new PathStringBuilder();
                var str = psb.GetNext();
            }
        }
    using System;
    //more usings ...
    
    namespace YourNamespace
    {
       // Overwrite everything between this braces   
    }

    I hope now it works ;)

    Greetings, Chris



    • Edited by DerChris88 Wednesday, October 3, 2018 10:37 PM
    Wednesday, October 3, 2018 10:35 PM
  • ...

    Line 8: } expected

    To find brace errors you can use this technic:

    number = 0;

    read every symbol;

    if it's { number ++;

    if it's } number --;

    if number is zero after you reached the last } every open brace is closed.

    else you have to many braces in the code.

    This is helpful to find errors in json files or bad formated code.

    Greetings, Chris


    • Edited by DerChris88 Wednesday, October 3, 2018 10:48 PM
    Wednesday, October 3, 2018 10:47 PM
  • If you would kindly write this code for me i will really appreciate it like a lot !!! In my macro i will just use a button to activate this code so each time it runs it will have to write the path which could be something Documents/test_1.cs then next time i activate the code again it would be Documents/test_2.cs

    Just watch the video and you will understand what i am trying to do ;)

    https://youtu.be/xYuidYmCWS8

    So, you want to increment (by 1), the number contained in the path (like Documents/test_1.cs) every time you get a new path, based on the previous one?

    Then, it is simple!

    My suggestion will shock the forum audience: don't use List<>, don't use Dictionary<>... but use... ... ...Tuple<>!!!

    And more: a small and very simple extension method.

    For instance:

    var tuple=Tuple.Create("Documents/abc/test_",7,".cs"); // and when you want a new path, // call an extension method this way: string newPath=tuple.GetNewPath(ref tuple));

    // Notice: the tuple updates itself!

    Here's my proposal, in full extension (method :):

    public static class Xt{
        public static string GetNewPath(this Tuple<string,int,string> t,ref Tuple<string,int,string> tuple){
            return string.Concat((tuple=Tuple.Create(tuple.Item1,1+tuple.Item2,tuple.Item3)).Item1,tuple.Item2,tuple.Item3);
        }
    }
    

    If you can test it like this, you'll get the corresponding output below:

    public static void Main(string[] args) { var tuple=Tuple.Create("Documents/abc/test_",7,".cs"); for(int i=0;i<5;++i) Console.WriteLine("\t{0}",tuple.GetNewPath(ref tuple)); }

      Documents/abc/test_8.cs
    Documents/abc/test_9.cs
    Documents/abc/test_10.cs
    Documents/abc/test_11.cs
    Documents/abc/test_12.cs


    • Proposed as answer by DerChris88 Tuesday, October 9, 2018 6:34 AM
    Thursday, October 4, 2018 2:40 AM
  •     class Program
        {
            public class PathStringBuilder
            {
                private int startValue = 1;
                private string extension = "cs";
                private string rootaPath = "Documents/";
                private string filenameBase = "test_";
    
                private const string NUMBER_FILE = "index.dat";
    
                private int getNumber()
                {
                    if (File.Exists(NUMBER_FILE))
                        using (var file = File.Open(NUMBER_FILE, FileMode.OpenOrCreate))
                        {
                            byte[] numberArray = new byte[4];
                            file.Read(numberArray, 0, 4);
                            int number = BitConverter.ToInt32(numberArray, 0);
                            file.Position = 0;
                            var test = BitConverter.GetBytes(number + 1);
                            file.Write(test, 0, 4);
                            return number;
                        }
                    else
                        File.WriteAllBytes(NUMBER_FILE, BitConverter.GetBytes(startValue + 1));
                    return startValue;
                }
    
                public string GetNext()
                {
                    return rootaPath + filenameBase + getNumber() + "." + extension;
                }
            }
    
            public static void Main(string[] args)
            {
                var psb = new PathStringBuilder();
                var str = psb.GetNext();
            }
        }
    using System;
    //more usings ...
    
    namespace YourNamespace
    {
       // Overwrite everything between this braces   
    }

    I hope now it works ;)

    Greetings, Chris



    nope it didn't work either it doesn't let me state Using system.... it has to be on the order of program and then main, i don't know why they did that...

    i am using this recorder:

    https://www.jitbit.com/macro-recorder/

    Thursday, October 4, 2018 7:20 AM
  • Use my trick to get the closing brace and start counting at the brace behind. If you reach 0 copy it from the { where you started to this brace. It's just copy paste...

    Or just copy the part where I posted the whole class Program and overwrite all!

    Greetings, Chris


    • Edited by DerChris88 Thursday, October 4, 2018 2:12 PM
    Thursday, October 4, 2018 10:11 AM
  • i don't understand sorry
    Thursday, October 4, 2018 1:29 PM
  • Use my trick to get the closing brace and start counting at the brace behind. If you reach 0 copy it from the { where you started to this brace. It's just copy paste...

    Or just copy the part where I posted the whole class Program and overwrite all!

    Greetings, Chris



    but anyways i still want to say thank you for your time and your cooperation i appreciated your help. just wanted you to know that its ok if i dont fix this i will ask in other forums as well i dont want to take much of your time nor i want to be a burden
    Thursday, October 4, 2018 3:28 PM
  • Looks like you have problems just by copy pasting the code. I tried to help you. I said just copy the hole class Program and overwrite yours!

    Here is an instruction of your recorder:

    https://www.jitbit.com/macro-recorder/c-code-snippets/

    It's written there how to do it.

    If this is not working for you now, then ... I'm afraid I can not help you.

    I'm sorry if this sounds rude but looks like you need to know much more about namespaces, classes and all other basic stuff of c#.

    Greetings, Chris


    • Edited by DerChris88 Thursday, October 4, 2018 3:55 PM
    Thursday, October 4, 2018 3:36 PM
  • i didn't saw that xD i had no idea but somehow i added like those namespaces or how you call them and now i get an ambiguous match found any ideas?

    using System.IO;
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading.Tasks;
      
    
    
    public class Program
    {
    	  public class PathStringBuilder
            {
                private int startValue = 1;
                private string extension = "cs";
                private string rootaPath = "Documents/";
                private string filenameBase = "test_";
    
                private const string NUMBER_FILE = "index.dat";
    
                private int getNumber()
                {
                    if (File.Exists(NUMBER_FILE))
                        using (var file = File.Open(NUMBER_FILE, FileMode.OpenOrCreate))
                        {
                            byte[] numberArray = new byte[4];
                            file.Read(numberArray, 0, 4);
                            int number = BitConverter.ToInt32(numberArray, 0);
                            file.Position = 0;
                            var test = BitConverter.GetBytes(number + 1);
                            file.Write(test, 0, 4);
                            return number;
                        }
                    else
                        File.WriteAllBytes(NUMBER_FILE, BitConverter.GetBytes(startValue + 1));
                    return startValue;
                }
    
                public string GetNext()
                {
                    return rootaPath + filenameBase + getNumber() + "." + extension;
                }
            }
    
          public static void Main(string[] args)
            {
                var psb = new PathStringBuilder();
                var str = psb.GetNext();
            }
    	public static void Main()
    	{
    		
    	}
    	
    }


    Thursday, October 4, 2018 10:00 PM
  • In these cases, it is a good idea to tell us exactly what the error says, so we know what we are looking for. It is a bit difficult to read that much code just knowing we are looking for an "ambiguous match".

    This time, however, it seems clear. You have two Main methods. Get rid of the second one.

    Normally, the compiler would allow methods with the same name, provided they have different arguments. But Main is a special case.

    Friday, October 5, 2018 3:49 AM
  • well it doesn't let me run the code otherwise if i remove the default main which is

    public static void Main()
    	{
    		
    	}
    	


    Friday, October 5, 2018 5:57 AM
  • In the first place, you should only need 1 main. Either Main() or Main(string[] args) will do as far as the compiler is concerned.

    When the program runs, it starts running Main. So the code you want to execute must start in there. If it is empty, the program will do nothing. If it has lines of code that don't produce any output, you won't see anything.

    Secondly, I have to again ask you to be more specific. When you say, "it doesn't let me run the code", what exactly do you mean? Do you get a compilation error? Do you get a runtime error? Do you get no errors but nothing seems to happen? It's a bit difficult to help when you keep making us guess.

    And to demonstrate what I mean about Main, the following code compiles and runs okay.

    using System;
    
    namespace ConsoleApp6
    {
       class Program
       {
          public static void Main(string[] args) // Note the version of Main.
          {
             Console.WriteLine("Hello");
          }
       }
    }

    Friday, October 5, 2018 6:08 AM
  • Try this:

    using System.IO; using System; public class Program { public class PathStringBuilder { private int startValue = 1; private string extension = "cs"; private string rootaPath = "Documents/"; private string filenameBase = "test_"; private const string NUMBER_FILE = "index.dat"; private int getNumber() { if (File.Exists(NUMBER_FILE)) using (var file = File.Open(NUMBER_FILE, FileMode.OpenOrCreate)) { byte[] numberArray = new byte[4]; file.Read(numberArray, 0, 4); int number = BitConverter.ToInt32(numberArray, 0); file.Position = 0; var test = BitConverter.GetBytes(number + 1); file.Write(test, 0, 4); return number; } else File.WriteAllBytes(NUMBER_FILE, BitConverter.GetBytes(startValue + 1)); return startValue; } public string GetNext() { return rootaPath + filenameBase + getNumber() + "." + extension; } } public static void Main() //Parameterless main { var psb = new PathStringBuilder(); var str = psb.GetNext();

    Console.WriteLine(str);


            Console.ReadLine();

    } }

    Copy paste all, overwrite all code in your macro recorder and tell us what's not working after you have done that ...

    Friday, October 5, 2018 7:08 PM
  • public static class Xt{
        public static string GetNewPath(this Tuple<string,int,string> t,ref Tuple<string,int,string> tuple){
            return string.Concat((tuple=Tuple.Create(tuple.Item1,1+tuple.Item2,tuple.Item3)).Item1,tuple.Item2,tuple.Item3);
        }
    }

    Certainly, a mutable tuple makes things much simpler:

    var tuple=ValueTuple.Create("Documents/abc/test_",1,".cs"); Func<string> getNewPath=()=>string.Concat(tuple.Item1,++tuple.Item2,tuple.Item3);

    // just 2 small lines of code. // tuple can be made a field or property, too.


    To test it:

    for(int i=0;i<15;++i)
        Console.WriteLine( getNewPath() );
    

    Saturday, October 6, 2018 6:47 AM
  • it doesn't do anything it doesn't display any errors... But from what i see i need to find an other approach because the command i were using ctrl +B to open that in sublime text it wouldn't just save the file like i wanted.

    And what i want to do from the sublime text 3 is to save it as in a specific folder and do the increment ;)

    Sunday, October 7, 2018 2:12 PM

  • Are you using Console.WriteLine to output the path? Are you sure it's doing nothing?

    You just told us to get a string ... That's what you got! It's like you buying a car engine and after you got it you are asking the seller where is the car?

    We all triing to help you, writing code matching your requirements you wrote and now you say it's not what you want and it was all for nothing?

    I'm a bit disapointed ...

    Sunday, October 7, 2018 2:39 PM
  • well,even the code didn't write anything on the path so ya.. and it wasn't all for nothing because i appreciated your help. and thanks for helping me out , i just don't want to waste your time... and that's why i am saying i need to find an other approach...

    I want to use sublime text 3  save as to a specific location and then increment the name(test_1) that is going to be saved. and then save it automatically.

    You can still find a way to do this if you wanna help but i don't want to be a burden...

    Monday, October 8, 2018 5:35 AM
  • Hi TheUninvited123,

    If the suggestion in the previous reply could not solve your question, could you provide code sample with error for us to test? And provide the details about what you want.

    Best Regards,

    Wendy


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Tuesday, October 9, 2018 2:35 AM
    Moderator
  • I want to use sublime text 3  save as to a specific location and then increment the name(test_1) that is going to be saved. and then save it automatically.
    Thursday, October 11, 2018 2:06 PM
  • Hi TheUninvited123,

    is this maybe a following requirement?

    And what do you mean by "Save as"? Do you want just to save this string in a txt file? Do you want to save other data in a file named like this string? If you are not telling us what you exactly want, then we can not help you.

    But how I already said, you need to know the basics of c# to programm it.

    Maybe you should rethink what you really want, close this topic, make a new one, use the code snippets from here as base and then we will see how we can help you.

    Greetings, Chris

    PS: But one more info: We are not freelancers for free, we just want to help people who are interessted in programming c#, we are not here to serve complete software solutions...




    • Edited by DerChris88 Thursday, October 11, 2018 2:27 PM
    Thursday, October 11, 2018 2:23 PM