简体   繁体   中英

Copy file using relative path

File.Copy(@"my program\\subfolder\\what i want to copy.txt", "C:\\Targetlocation");

如何使用相对路径将文本文件从一个文件夹复制到另一个文件夹。

To execute the File.Copy the source and destination will be a valid file path. in your case the destination is a folder not File. in this case you may get some exception like

Could not find a part of the path 'F:\\New folder'

While executing the application, the current directory will be the bin folder. you need to specify the relative path from there. Let my program/subfolder be the folders in your solution, so the code for this will be like this:

string sourcePath = "../../my program/subfolder/what i want to copy.txt";
string destinationPath = @"C:\Targetlocation\copyFile.txt"
File.Copy(sourcePath, destinationPath );

Where ../ will help you to move one step back from the current directory. One more thing you have to care is the third optional parameter in the File.Copy method. By passing true for this parameter will help you to overwrite the contents of the existing file.Also make sure that the folder C:\\Targetlocation is existing, as this will not create the folder for you.

File.Copy(@"subfolder\\what i want to copy.txt", "C:\\Targetlocation\\TargetFilePath.txt");

The sourceFileName and destFileName parameters can specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory. This method does not support wildcard characters in the parameters.

File.Copy on MSDN

Make sure your target directory exists. You can use Directory.CreateDirectory

Directory.CreateDirectory("C:\\Targetlocation");

With Directory.CreateDirectory() , you don't have to check if the directory exists. From documentation:

Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. The path parameter specifies a directory path, not a file path. If the directory already exists, this method does nothing.

// Remove path from the file name.
    string fName = f.Substring(sourceDir.Length + 1);

    try
    {
        // Will not overwrite if the destination file already exists.
        File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
    }

You can provide the relative path from your current working directory which can be checked via Environment.CurrentDirectoy.

For example if your current working directory is D:\\App, your source file location is D:\\App\\Res\\Source.txt and your target location is D:\\App\\Res\\Test\\target.txt then your code snippet will be -

File.Copy(Res\\Source.txt, Res\\Test\\target.txt); 

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