【问题标题】:C# move file with 2 mapped drivesC# 使用 2 个映射驱动器移动文件
【发布时间】:2018-03-29 08:45:01
【问题描述】:

我需要使用下面的代码将名为 A:\ 的映射文件夹中存在的文件移动到另一个映射文件夹 B:\

File.Move(@"A:\file.txt",@"B:\");

它返回下面的错误

Could not find file 'A:\file.txt'.

我尝试在文件夹资源管理器中打开 A:\file.txt 并正常打开文件

【问题讨论】:

  • 根据 MSDN,您需要指定目标文件名,而不仅仅是路径。
  • Msdnpublic static void Move( string sourceFileName, string destFileName )
  • File.Exist(@"A:\file.txt") 带给你什么
  • 没有其他信息,这将是一个没有复制。

标签: c# mapped-drive file-move


【解决方案1】:

看起来File.Move 仅适用于本地驱动器上的文件。

File.Move 实际上调用了MoveFile,它指出 sourcedestination 都应该是:

本地计算机上文件或目录的当前名称。

结合使用File.CopyFile.Delete 会更好。

将文件从A复制到B,然后从A删除文件。

【讨论】:

  • 来自 Msdn :“备注:此方法适用于磁盘卷”
【解决方案2】:

如前所述,File.Move 需要 sourceFileName 和 destFileName。
而且您在第二个参数中缺少文件名。

如果您想移动文件并保持相同的名称,您可以使用 GetFileName 从 sourceFileName 中提取文件名并在您的 destFileName 中使用它

string sourceFileName = @"V:\Nothing.txt";
string destPath   = @"T:\";
var fileName = Path.GetFileName(sourceFileName);

File.Move(sourceFileName, destPath + fileName );

这是一个调试代码:

public static void Main() 
{
    string path = @"c:\temp\MyTest.txt";
    string path2 = @"c:\temp2\MyTest.txt";
    try 
    {
        if (!File.Exists(path)) 
        {
            // This statement ensures that the file is created,
            // but the handle is not kept.
            Console.WriteLine("The original file does not exists, let's Create it.");
            using (FileStream fs = File.Create(path)) {}
        }

        // Ensure that the target does not exist.
        if (File.Exists(path2)) {           
            Console.WriteLine("The target file already exists, let's Delete it.");
            File.Delete(path2);
        }

        // Move the file.
        File.Move(path, path2);
        Console.WriteLine("{0} was moved to {1}.", path, path2);

        // See if the original exists now.
        if (File.Exists(path)) 
        {
            Console.WriteLine("The original file still exists, which is unexpected.");
        } 
        else 
        {
            Console.WriteLine("The original file no longer exists, which is expected.");
        }   

    } 
    catch (Exception e) 
    {
        Console.WriteLine("The process failed: {0}", e.ToString());
    }
}

【讨论】:

  • 同样的问题:找不到文件'A:\file.txt
  • 请使用msdn代码示例。告诉我们您的问题是什么
  • 以下 2 个代码均无效:File.Move(@"A:\\file.txt", @"B:\\" + Path.GetFileName("A:\\file.txt")); 和此 File.Move("A:\\file.txt", "B:\\" + Path.GetFileName("A:\\file.txt"));
  • 同样的问题:无法文件Could not find file 'A:\\file.txt
  • 请您按照这些简单的步骤操作: 1/;单击File.Move 2/ 的任何 MSDN 链接。转到代码示例 3/。将其复制到您的代码中。使用示例空 txt 文件(请不是您的真实文件) 4/.告诉我们失败的地方...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-03-28
  • 2017-10-03
  • 1970-01-01
  • 2021-02-23
  • 2020-05-02
  • 2017-07-19
  • 1970-01-01
相关资源
最近更新 更多