如何将文件从文件夹a移动到文件夹b?

3
我希望能够将文件从一个目录复制到另一个目录,但是不起作用。出现的错误如下:

无法创建目录,可以是因为它已存在或其他原因

这是我的代码:
string uplaydir = "";
using (StreamReader sr = new StreamReader("src\\SYSTEM\\launcherfiles\\uplay_dir.txt"))
{
    uplaydir = sr.ReadLine();
}
label2.Text = "Installing";
ExtractZipFile(@"src\\SYSTEM\\launcherfiles\\updatefiles\\vmr.zip", @"src\\SYSTEM\\launcherfiles\\updatetemp");
label2.Text = "Done!";
File.Copy(@"src\\SYSTEM\\launcherfiles\\updatetemp\\ubi", @uplaydir);

uplay_dir.txt 位于 c:\test\

uplay_cm.dll 位于 src\\SYSTEM\\launcherfiles\\updatetemp\\ubi

我该如何修复?


你正在混合使用转义字符串和逐字字符串 ("text" vs @"text")。 - sara
1个回答

5

这些MSDN链接将向您展示如何操作。

按照以下代码在目录之间复制文件:

string fileName = "test.txt";
string sourcePath = @"C:\Users\Public\TestFolder";
string targetPath =  @"C:\Users\Public\TestFolder\SubDir";

// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);

// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
    System.IO.Directory.CreateDirectory(targetPath);
}

// To copy a file to another location and 
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);

// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
//       in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
    string[] files = System.IO.Directory.GetFiles(sourcePath);

    // Copy the files and overwrite destination files if they already exist.
    foreach (string s in files)
    {
        // Use static Path methods to extract only the file name from the path.
        fileName = System.IO.Path.GetFileName(s);
        destFile = System.IO.Path.Combine(targetPath, fileName);
        System.IO.File.Copy(s, destFile, true);
    }
}
else
{
    Console.WriteLine("Source path does not exist!");
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接