我有一个文件夹:
c:\test
我正在尝试运行这段代码:
File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test");
我遇到了异常:
文件已存在
输出目录肯定存在,输入文件也在那里。
你需要的是:
if (!File.Exists(@"c:\test\Test\SomeFile.txt")) {
File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test\SomeFile.txt");
}
或者if (File.Exists(@"c:\test\Test\SomeFile.txt")) {
File.Delete(@"c:\test\Test\SomeFile.txt");
}
File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test\SomeFile.txt");
这将会:
编辑:我应该澄清一下我的回答,尽管它是最受欢迎的!File.Move的第二个参数应该是 目标文件 - 而不是文件夹。您将第二个参数指定为目标文件夹,而不是目标文件名 - 这就是File.Move所需要的。
因此,您的第二个参数应该是c:\test\Test\SomeFile.txt
。
您需要将它移动到另一个文件中(而不是文件夹),这也可以用于重命名。
移动:
File.Move(@"c:\test\SomeFile.txt", @"c:\test\Test\SomeFile.txt");
重命名:
File.Move(@"c:\test\SomeFile.txt", @"c:\test\SomeFile2.txt");
在您的示例中显示“文件已存在”的原因是,C:\test\Test
尝试创建一个没有扩展名的文件 Test
,但由于已经存在同名的文件夹,所以无法创建。
.d
作为目录后缀,即使同名的文件已经存在。谢谢! - Jamie Howarth就个人而言,我更喜欢这种方法。 这将覆盖目标文件中的内容,删除源文件,并且在复制失败时也会防止删除源文件。
string source = @"c:\test\SomeFile.txt";
string destination = @"c:\test\test\SomeFile.txt";
try
{
File.Copy(source, destination, true);
File.Delete(source);
}
catch
{
//some error handling
}
MoveFileEx()
- 将flags
参数设置为11(MOVEFILE_COPY_ALLOWED | MOVEFILE_REPLACE_EXISTING | MOVEFILE_WRITE_THROUGH
)。[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
static extern bool MoveFileEx(string existingFileName, string newFileName, int flags);
或者,你可以直接打电话
Microsoft.VisualBasic.FileIO.FileSystem.MoveFile(existingFileName, newFileName, true);
在添加了Microsoft.VisualBasic作为参考之后。
在 .NET Core 3.0 及以后的版本中,您可以调用 Move(String, String, Boolean) 方法,并将参数 overwrite 设置为 true,这将替换文件(如果存在)。
如果文件确实存在,且您想要替换它,请使用下面的代码:
string file = "c:\test\SomeFile.txt"
string moveTo = "c:\test\test\SomeFile.txt"
if (File.Exists(moveTo))
{
File.Delete(moveTo);
}
File.Move(file, moveTo);
Move(String,String,Boolean)
。但这似乎是一个错误? - Kevin ScharnhorstMicrosoft.VisualBasic.FileIO.FileSystem.MoveFile(Source, Destination, True)
。最后一个参数是覆盖开关,而 System.IO.File.Move
没有此功能。string newFileLocation = @"c:\test\Test\SomeFile.txt";
while (File.Exists(newFileLocation)) {
newFileLocation = newFileLocation.Split('.')[0] + "_copy." + newFileLocation.Split('.')[1];
}
File.Move(@"c:\test\SomeFile.txt", newFileLocation);
FileMoveEx()
这样有用的东西。因此,.net缺少类似于POSIX的FS层。.net确实公开了File.Replace()
,但试图使用它来实现类似于POSIX的rename()
会导致竞争条件。如果框架公开了类似于POSIX的rename()
,将使人们的生活更轻松,并允许人们编写更纯净(少P/Invoke)的代码。 - binki