Start New Discussion within our Software Development Community

I created an app that reads two columns from excel file and search for each file in column A. if file is found then it is renamed to what column b says and moved to a separate folder.

This part of the code that i am having issue, please help!!!

DirectoryInfo di = new DirectoryInfo(sourceFile);
FileInfo[] files = di.GetFiles(oldName, SearchOption.AllDirectories);

foreach (FileInfo file in files)
     file.MoveTo(destinationFile + @"\\" + newName);

In debugging mode:
this is what i see in each variable

sourceFile = "c:\test"
oldName = "128-421.jpg"
newName = "128.jpg"
di = "C:\\test"
files = {System.IO.FileInfo[0]}
file = Null

Why do i keep getting Null in variable file.

Hi there,

Here's some code that I hope it will help you.

// Folder path;
            string sourcePath = Application.StartupPath;

            DirectoryInfo di = new DirectoryInfo(sourcePath);

            // File name;
            string oldName = "file.txt";

            FileInfo[] files = di.GetFiles(oldName, SearchOption.TopDirectoryOnly);

            // Path to destination folder;
            string destinationPath = sourcePath + @"\Folder\";
            // New name of file;
            string newName = "newfile.txt";

            foreach (FileInfo file in files)
                file.MoveTo(destinationPath + newName);

This is having source folder where your executable runs,
Destination folder is a folder inside the source folder named 'Folder'.

And note, if you use @ you shouldn't escape the bar... Either use "\\" or @"\". Using @"\\" as in your code above will give you as result "\\" and that will give you an invalid path.
See some explanation about it here


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