Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move a file from one directory to another

Tags:

c#

directory

move

I created a zip file/folder with DotNetZip. I'm trying to move that file from the original directory/folder to another, e.g. My Documents. So far I have done the following, but it gives me an error saying that it could not find part of the path.

private static void Move()
{
    try
    {
        Directory.Move(@"Debug\Settings.zip", IO.Paths.Enviroment.MyDocuments);
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

UPDATE: So I've played with it a bit and laughed not because I fixed it but because it's weird. I used both File.Move() and Directory.Move() and changed both.Move(@"Debug\Settings.zip",...); to both.Move(@"Settings.zip",...); and then get get an an error saying Cannot create a file when that file already exists.

Directory Tree

like image 714
iwatakeshi Avatar asked Dec 10 '25 00:12

iwatakeshi


2 Answers

While it may seem strange to use Directory.Move to move a file, (I'd use File.Move instead), Jean-Philippe Leclerc points out that it will work.

The problem is with the path Debug\Settings.zip:

All relative paths are relative to the working directory. By default the working directory is the folder in which the assembly (your program) is executed, and while debugging that is the bin\Debug subfolder of your project. So your path Debug\Settings.zip is expanded to a path like:

C:\..\MyProject\bin\Debug\Debug\Settings.zip

This is probably not what you meant. You meant just "Settings.zip".

The fact that it's a ZIP is irrelevant.

like image 94
Daniel A.A. Pelsmaeker Avatar answered Dec 11 '25 12:12

Daniel A.A. Pelsmaeker


Use System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) to get your MyDocuments path.

like image 44
Stéphanie L Avatar answered Dec 11 '25 12:12

Stéphanie L



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!