使用相对路径复制文件

Copy file using relative path

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

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

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

确保您的目标目录存在。您可以使用 Directory.CreateDirectory

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

使用Directory.CreateDirectory(),您不必检查目录是否存在。来自文档:

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));
    }

要执行 File.Copy,源和目标将是一个有效的文件路径。在您的情况下,目标是文件夹而不是文件。在这种情况下,您可能会遇到一些异常,例如

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

在执行应用程序时,当前目录将是 bin 文件夹。您需要从那里指定相对路径。让 my program/subfolder 成为您解决方案中的文件夹,因此代码如下:

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

其中 ../ 将帮助您从当前目录后退一步。您还需要注意的另一件事是 File.Copy 方法中的第三个可选参数。通过为该参数传递 true 将帮助您覆盖现有 file.Also 的内容,确保文件夹 C:\Targetlocation 存在,因为这不会为您创建文件夹。

您可以提供当前工作目录的相对路径,可以通过 Environment.CurrentDirectoy 检查。

例如,如果您当前的工作目录是 D:\App,您的源文件位置是 D:\App\Res\Source.txt,您的目标位置是 D:\App\Res\Test\target.txt 那么您的代码片段将是 -

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