I have a folder with over 2000+ MS Excel 2010 .XLSX spreadsheets and I need to perform the following actions:
-
I need to open each individual file
-
Copy the content of cell B4 (+ each file has unique content on cell B4), and
-
append the content of cell B4 to the original file name
How can I fix this error so I can successfully rename my spreadsheets as mentioned above?
//file rename code
DirectoryInfo d = new DirectoryInfo(@"C:\Torename\");
FileInfo[] infos = d.GetFiles();
foreach (FileInfo f in infos)
{
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = excel.Workbooks.Open(f.FullName);
Worksheet excelSheet = wb.ActiveSheet;
//Read the first cell
string test = excelSheet.Cells[4, 2].Value.ToString();
File.Move(f.Name, new_filename);
***Thank you for your assistance that did the trick
File.Move(f.FullName, new_filename);
You have to use FullName
, you need the full path.
Edit: Not part of your Question, but:
I’m not sure how Workbooks.Open
works, but if you run into errors you might close the file before renaming it.
Also Adams comment.
Answer:
Close the workbook before moving it. Make sure to release all the resources associated with that file.
And make sure you use the whole path in the names