I am trying to send files from one directory to another and then renaming them to a ordered list of numbered files. The only problem is when you do it once and then do it again the file numbering goes back to 0 so is unable to move as file name already exists. How do it get it to move and rename from the last named file that was moved and renamed?


Private void butSort3_Click(object sender, EventArgs e)
            DirectoryInfo di = new DirectoryInfo(@"C:\new3");
            FileInfo[] fiArr = di.GetFiles("*.txt");
            int iCtr = 0;

                foreach (FileInfo fri in fiArr)
                    MessageBox.Show(fri.FullName.ToString(), "File Manager", MessageBoxButtons.OK);
                    fri.MoveTo(@"C:\new4\File" + "1(" + iCtr
                    + ").txt");

You have a couple of choices.
You can store the current file number somewhere so you can resume from that number, or you can loop through the numbers until you find the lowest that doesnt already exist.
If you do the first you need to decide the scope of the number. If you want it to track the file number for as long as the application is running then store it in a variable in your main form. If you want it to remember the number after you close and reopen your app then you need to save it to file somewhere (either a textfile in the applicaitons root directory or using the Settings files).
If you dont want to store the number, you can use a loop to iterate through the possible file numbers, checking if each file already exists, until you find the first number you havent already used. This will ensure you dont attempt to reuse numbers, but if you have a lot of files it will become pretty slow.

This article has been dead for over six months. Start a new discussion instead.