How to move files into folders using C# and Excel
Introduction
This C# recipe shows how you can move files into folders by using Excel.
Use Case
I have received hundreds of image files and saved them on my PC. I need to move these image files into categorised subfolders. I have a spreadsheet which shows where each image needs to move to.
Ingredients
The recipe uses the EPPlus library version 4.5.3.3. This is the last version of EPPlus under the LGPL License (aka free for commercial uses). You can install it using Nuget Package manager:
Install-Package EPPlus -Version 4.5.3.3
C# Code
var path = @"C:\Temp\ExcelRecipes\MovingFiles\";
var fileName = "MoveFiles.xlsx";
// open excel file using EPPlus
using (ExcelPackage excelFile = new ExcelPackage(new FileInfo(path + fileName)))
{
// select first worksheet
var worksheet = excelFile.Workbook.Worksheets.First();
// read contents of excel file and map to list of movefileinfo objects
var listOfImages = new List<MoveFileInfo>();
int rowCount = worksheet.Dimension.End.Row; //get row count
for (int row = 2; row <= rowCount; row++)
{
var moveFileInfo = new MoveFileInfo();
moveFileInfo.FileName = worksheet.Cells[row, 1].Text;
moveFileInfo.Section = worksheet.Cells[row, 2].Text;
moveFileInfo.Category = worksheet.Cells[row, 3].Text;
moveFileInfo.SourceFolder = worksheet.Cells[row, 4].Text;
moveFileInfo.DestinationFolder = worksheet.Cells[row, 5].Text;
moveFileInfo.Moved = worksheet.Cells[row, 6].Text;
moveFileInfo.ExcelRow = row;
listOfImages.Add(moveFileInfo);
}
// move each image - which has not been marked as moved - to its destination folder
foreach (var i in listOfImages.Where(u=> u.Moved == false))
{
var sourceFileName = i.SourceFolder + i.FileName;
// does file exist
if (sourceFileName.FileExists())
{
// if yes, check if destination folder exists. if not create folder
if (!Directory.Exists(i.DestinationFolder))
Directory.CreateDirectory(i.DestinationFolder);
// move file
File.Move(sourceFileName, destFileName: i.DestinationFolder + i.FileName);
// mark it as moved on excel template
worksheet.Cells[i.ExcelRow, 6].Value = "TRUE";
}
else
{
// note that file does not exist in the moved column
worksheet.Cells[i.ExcelRow, 6].Value = $"File {i.FileName} does not exist in {i.SourceFolder}";
}
}
excelFile.Save();
}
public class MoveFileInfo
{
public string FileName { get; set; }
public string Section { get; set; }
public string Category { get; set; }
public string SourceFolder { get; set; }
public string DestinationFolder { get; set; }
public string Moved { get; set; }
public int ExcelRow { get; set; }
}