4

这是来自 Microsoft 的代码示例,具有不同的文件位置,但无法正常工作:

 string fileName = "test1.txt";
 string sourcePath = @"C:\";
 string targetPath = @"C:\Test\";

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

 System.IO.File.Copy(sourceFile, destFile, true);

它找不到源文件。如果我设置一个断点,这就是我得到的:

    args    {string[0]} string[]
    fileName    "test1.txt" string
    sourcePath  "C:\\"  string
    targetPath  "C:\\Test\\"    string
    sourceFile  "C:\\test1.txt" string
    destFile    "C:\\Test\\test1.txt"   string

因此,即使使用逐字字符串,它看起来也将反斜杠加倍。(毫无疑问,我在 C 中有一个 test1.txt 文件:)有什么想法吗?谢谢!

4

5 回答 5

7

常见的故障模式有3种:

  1. 源文件C:\test1.txt不存在。
  2. 目标文件C:\Test\test1.txt存在但只读。
  3. 目标目录C:\Test不存在。

我的猜测是第 3 项是问题所在,如果是这样,您需要在调用File.Copy. 如果是这种情况,您将看到一个DirectoryNotFoundException. 您可以使用Directory.CreateDirectory来确保目标目录存在。

于 2012-04-10T14:15:09.767 回答
4

双反斜杠是在字符串中表示反斜杠的常用方式。当您使用 @ 时,您表示您不想解释任何转义序列(除其他事项外,请参阅此处以获取更多信息,在“文字”下)

所以问题是不同的。C:\test1.txt 和 C:\Test 是否存在?您是否有权在 targetPath 中写入?

尝试以下操作(根据需要添加异常处理和更多错误检查)

if (!Directory.Exists(targetPath)) {
    Directory.CreateDirectory(targetPath);
}
if (File.Exists(sourceFile)) {
    File.Copy(sourceFile,destFile,true);
}
于 2012-04-10T14:14:43.197 回答
0

如果您遇到问题,请尝试查看以下示例:

using System;
using System.IO;
class Test 
{
    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";
        string path2 = path + "temp";

        try 
        {
            // Create the file and clean up handles.
            using (FileStream fs = File.Create(path)) {}

            // Ensure that the target does not exist.
            File.Delete(path2);

            // Copy the file.
            File.Copy(path, path2);
            Console.WriteLine("{0} copied to {1}", path, path2);

            // Try to copy the same file again, which should succeed.
            File.Copy(path, path2, true);
            Console.WriteLine("The second Copy operation succeeded, which was expected.");
        } 

        catch 
        {
            Console.WriteLine("Double copy is not allowed, which was not expected.");
        }
    }
}

取自:http: //msdn.microsoft.com/en-us/library/system.io.file.copy (v=vs.71).aspx

于 2012-04-10T14:17:15.807 回答
0

反斜杠加倍是正确的,我认为你的问题是文件名。尝试在没有该操作的情况下读取文件,但在查看是否“隐藏已知类型的扩展”之前,文件名应该是 test1.txt.txt :)

于 2012-04-10T14:17:17.320 回答
0

要准确查看问题所在,您可以将代码包装在一个try-catch块中:

try { // Code that can throw an exception }
catch (Exception ex)
{
    // Show what went wrong
    // Use Console.Write() if you are using a console
    MessageBox.Show(ex.Message, "Error!");
}

最可能的问题是缺少源文件、目标文件夹不存在或您无权访问该位置。

在 Windows 7 上,我注意到您需要管理员权限才能直接写入安装操作系统的驱动器的根目录(通常c:\)。尝试在该位置写入文件或创建目录可能会失败,因此我建议您使用其他位置。

于 2012-04-10T15:11:27.867 回答