简体   繁体   中英

Move a file from one directory to another

I created a zip file/folder with DotNetZip. I'm trying to move that file from the original directory/folder to another, eg 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.

目录树

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.

could not find part of the path - The error seems like the Relative Path to your file Settings.Zip is not a valid path!


You need to use File.Move , Directory.Move will move the entire content of the Directory to different folder.

File.Move : Only moves the file to a specified location

private static void Move()
        {
            try
            {
                File.Move(@"Debug\Settings.zip", System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

使用System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)获取MyDocuments路径。

Fixed! The issues were first the "Debug\\Settings.zip" should have been "Settings.zip" or @"Settings.zip" and finally destination should not just be System.IO.File.Move(@"Settings.zip", System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop)); but System.IO.File.Move(@"Settings.zip", System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop) + @"\\Settings.zip"); Basically, add the file name and the extension of the file at the end of the destination string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM