我需要使用以下代码将名为A:
的映射文件夹中存在的文件移动到另一个映射文件夹B:
File.Move(@"A:file.txt",@"B:");
它返回以下错误
Could not find file 'A:file.txt'.
我尝试在文件夹资源管理器中打开 A:\file.txt,它正常打开文件
看起来File.Move
仅适用于本地驱动器上的文件。
File.Move
实际上调用了MoveFile
,其中指出源和目标都应该是:
本地计算机上文件或目录的当前名称。
使用File.Copy
和File.Delete
的组合会更好。
将文件从A
复制到B
,然后从A
中删除该文件。
如前所述,File.Move
需要sourceFileName和destFileName。
并且您在第二个参数中缺少文件名。
如果要移动文件并保持相同的名称,则可以使用GetFileName
从源文件名中提取文件名,并在dest文件名中使用它
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:tempMyTest.txt";
string path2 = @"c:temp2MyTest.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());
}
}