Click here to Skip to main content
15,901,666 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

Need to rename file in datagrid view ,

old file name test.txt and need to add prefix as tes001test.txt and need to increment number to 002 for the next file .

What I have tried:

int CheckBoxRowCounter = 0;
            for (int i = 0; i < dataGridView1.RowCount; i++) {
                if (Convert.ToBoolean(dataGridView1.Rows[i].Cells[0].Value)) {
                    CheckBoxRowCounter++;
                }
            }
            if (CheckBoxRowCounter > 0)
            {
                for (int i = 0; i < dataGridView1.RowCount; i++)
                {

                    if (Convert.ToBoolean(dataGridView1.Rows[i].Cells[0].Value))
                    {
                        string SourceFilePath = dataGridView1.Rows[i].Cells[1].Value.ToString();
                        string FileName = new System.IO.FileInfo(SourceFilePath).Name;
                        var prefix = Regex.Match(SourceFilePath, "^\\D+").Value;
                        var number = Regex.Replace(SourceFilePath, "^\\D+", "");
                        var r = int.Parse(number) + 1;
                        var newstring = prefix + r.ToString(new string('0', number.Length));
                    }
                }
Posted
Updated 12-Jul-18 21:39pm

1 solution

First off, check your regex: that won't work:
^\D+
Matches numbers at the start of the text, and your description doesn't show that: "tes001text.txt" does not match your pattern at all.
^tes\D+
would, but ... Regex.Replace Method (String, String) (System.Text.RegularExpressions)[^] does not return the "bit it removed", so your attempt to parse the number is goign to fail as well because you have specifcally removed the number from the string you are trying to parse!

Stop guessing: read up on Regexes, and get a copy of Expresso[^] - it's free, and it examines, tests, and generates Regular expressions.

But... why the heck are you even trying to parse the number when you presumably need the number from the previous row to work out what number to give this one?
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900