C#移动带有2个映射驱动器的文件

时间:2018-03-29 08:45:01

标签: c# mapped-drive file-move

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

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

它返回

下面的错误
Could not find file 'A:\file.txt'.

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

2 个答案:

答案 0 :(得分:1)

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

File.Move实际上调用了MoveFile,其中指出 source destination 应该是:

  

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

使用File.CopyFile.Delete的组合会更好。

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

答案 1 :(得分:0)

如前所述,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());
    }
}