merv
merv

Reputation: 331

Rename all file names in a directory using datagridview column value

I have a datagridview

ID     Name
-----------
1      ABC    
2      DEF    
3      XYZ

I have 3 files in a directory

ABC.csv
DEF.csv
XYZ.csv

How do I loop through the file names and rename them according to their ID, so that they become

1.csv
2.csv
3.csv

Here's my code but I do not know to do the retrieve the ID from datagridview. Any help would be much appreciated! Thank you. :)

DirectoryInfo d = new DirectoryInfo(sourceDirCSV);
FileInfo[] infos = d.GetFiles();
foreach (FileInfo f in infos)
{
    try
    {
        File.Move(f.FullName, f.FullName.ToString().Replace(Path.GetFileNameWithoutExtension(sourceDirCSV), "???"));
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}

Upvotes: 0

Views: 669

Answers (2)

Pabinator
Pabinator

Reputation: 1641

I will do something like this:

        string sourceDir = "D:\\Temp\\";
        DirectoryInfo d = new DirectoryInfo(sourceDir);
        string newFileName = "";
        string oldFileName = "";
        foreach (DataGridViewRow row in dataGridView1.Rows)
        {
            newFileName = sourceDir + row.Cells["ID"].Value.ToString() + ".csv";
            oldFileName = sourceDir + row.Cells["Name"].Value.ToString() + ".csv";

            if (File.Exists(oldFileName))
            {
                File.Move(oldFileName, newFileName);
            }                
        }

Upvotes: 1

SHEKHAR SHETE
SHEKHAR SHETE

Reputation: 6066

You can Try with the Following:

Loop through all rows of DataGrid:

foreach(DataGridViewRow row in DataGridView1.Rows)
{
    string colVal=row.Cells(1).Value.ToString();
    foreach (string currFilename in Directory.GetFiles(path, "*.csv").Select(Path.GetFileName))
    {
      //Path.GetFileNameWithoutExtension(fi.Name): this will get file name without extension
       if(colVal.Equals(currFilename))
       {
        //rename file here
       }
    }
}

Please make changes according to your requirement dont use "as is".

hope this helps you!

Upvotes: 1

Related Questions