Click here to Skip to main content
15,888,286 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am not able to move the file from one location to another location. Please help to debug the issue.

What I have tried:

C#
   var filenames = Directory.GetFiles(filepath, "*.DXT");
foreach (var filename in filenames)
//Here i am reading the file for some operations..
         var readFile = File.ReadAllLines(filename);
         List<string[]> instantPackets = readFileAccProtocol.packet(obj["instant"]["header"].ToString(), readFile);

//Now i want to move the file to new location
File.Move(filename, moveTo);

//Here move to contains the destination path where i want to move my file
Posted
Updated 16-May-22 2:48am
v2
Comments
Rajeev Jayaram 16-May-22 6:51am    
What error you are getting? - Did you close the filestream before moving?
Himansh jain 16-May-22 7:03am    
- $exception {"Cannot create a file when that file already exists."} System.IO.IOException

i am getting this exception

There are two possibilities:
1) The file genuinely exists in the destination in which case you need to delete it first: File.Exists(String) Method (System.IO) | Microsoft Docs[^] and File.Delete(String) Method (System.IO) | Microsoft Docs[^] are the methods you need.

2) The destination is a folder rather than a file name. If this is the case, the file can't be moved as it would overwrite the folder. Check your destination - you may need to append the filename:
C#
string file = @"D:\Test Data\MyFile.json";
string dest = Path.Combine(@"D:\Test Data\Test", Path.GetFileName(file));
File.Move (file, dest);
 
Share this answer
 
moveTo should be the target filename, not just a folder name. You can use something like:
C#
moveToFullPath = Path.Join(moveTo, Path.GetFileName(filename));
File.Move(filename, moveToFullPath);

to keep the filename the same as it was in the source.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900