Moving files from one folder to another – ‘File is being used by another process’

I’m creating a little desktop application that will allow me to specify 3 fields(with example data):
Root Folder – D:ProgrammingStorage for testingFileMoverFolder_1

Destination Folder – D:ProgrammingStorage for testingFileMoverFolder_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_1Test.txt”

Run Create new files
Destination Folder : “Folder_2Test.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:ProgrammingStorage for testingFileMoverFolder_1

destinationFolder = D:ProgrammingStorage for testingFileMoverFolder_2

newFileDestination = D:ProgrammingStorage for testingFileMoverFolder_2Test1.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]; 


submitted by /u/z-2
[link] [comments]

Leave a Reply