I'm creating a little desktop application that will allow me to specify 3 fields(with example data):
Folder - D:\Programming\Storage for testing\FileMover\Folder_1
Destination Folder - D:\Programming\Storage for testing\FileMover\Folder_2
File Type - .txt
So I want to move all of the files with the file type .txt from the Root Folder to the Destination Folder.I read using 'Directory.Move()' requires you to move the file to another file within the specified directory. So I wrote a little function that builds up the file path for the new file but keep the name so:
Root Folder File : "\Folder_1\Test.txt"
Run Create new filesDestination Folder : "\Folder_2\Test.txt" This bit works but when I attempt Directory.Move() it says the file in the destination folder is in use. How can I go about making sure it is not in use before the move?
Some Variables to help understand:
FileType = "txt" RootDirectory = D:\Programming\Storage for testing\FileMover\Folder_1
destinationFolder = D:\Programming\Storage for testing\FileMover\Folder_2
newFileDestination = D:\Programming\Storage for testing\FileMover\Folder_2\Test1.txt
filesToCopy = every file within Folder_1 with the file type of FileType
public override string[] CreateEmptyFiles()
{
var fileTypeFormat = "*." + FileType;
var filesToCopy = Directory.GetFiles(RootDirectory, fileTypeFormat);
//file is the file path of the root directory including the file
foreach (var file in filesToCopy)
{
//Split the file hierarchy into a string array
var directoryHierarchy = file.Split('\\');
//Get the file name
var fileName = directoryHierarchy[directoryHierarchy.Length - 1];
//Create the new file path
var newFileDestination = destinationFolder + "\\" + fileName;
using (FileStream fileStream = new FileStream(newFileDestination, FileMode.Create))
{
//Create the new file
File.Create(newFileDestination);
}
//Exception thrown here
Directory.Move(newFileDestination, file);
}
return new string[10];
}