0

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

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

它返回下面的错误

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

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

4

2 回答 2

1

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

File.Move实际上调用MoveFilewhich 声明目标都应该是:

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

File.Copy使用和的组合会更好File.Delete

将文件从 复制AB,然后从 中删除文件A

于 2018-03-29T08:59:23.553 回答
0

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

如果您想移动文件并保持相同的名称,您可以从 sourceFileName 中提取文件名GetFileName并在您的 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());
    }
}
于 2018-03-29T09:18:59.210 回答