简体   繁体   English

重命名现有文件名

[英]Rename existing file name

I have the following code which copies a file to a specific folder and then renames it. 我有以下代码将文件复制到特定文件夹,然后重命名它。 When a file with that name already exists I get the following exception: 当具有该名称的文件已存在时,我收到以下异常:

Cannot create a file when that file already exists

Is there a way to overwrite the file and rename it? 有没有办法覆盖文件并重命名? or I should delete the old one and then change the name? 或者我应该删除旧的然后更改名称?

Here is my code: 这是我的代码:

 File.Copy(FileLocation, NewFileLocation, true);
 //Rename:
 File.Move(Path.Combine(NewFileLocation, fileName), Path.Combine(NewFileLocation, "File.txt"));               

Try to use only: 尽量只使用:

if (File.Exists("newfilename"))
{
    System.IO.File.Delete("newfilename");
}

System.IO.File.Move("oldfilename", "newfilename");

One simple option is to delete the file if it exists: 一个简单的选项是删除文件(如果存在):

if (System.IO.File.Exists(newFile)) System.IO.File.Delete(newFile);
System.IO.File.Move(oldFile, newFile);

Something like that should work. 这样的事情应该有效。

You're correct, File.Move will throw an IOException if/when the filename already exists. 你是对的,如果/当文件名已存在时, File.Move将抛出IOException So, to overcome that you can perform a quick check before the move. 因此,为了克服这一点,您可以在移动前进行快速检查。 eg 例如

if (File.Exists(destinationFilename))
{
    File.Delete(destinationFilename);
}
File.Move(sourceFilename, destinationFilename);

You should use File.Exists rather than letting the Exception throw. 您应该使用File.Exists而不是让Exception抛出。 You can then handle if the file should be overwrote or renamed. 然后,您可以处理文件是否应该被覆盖或重命名。

Step 1 : as a first step identify wether the file exists or not before copying the file. 步骤1:作为第一步,在复制文件之前识别文件是否存在。
using File.Exists() method 使用File.Exists()方法

Step 2: if the file already exists with same name then delete the existing file using File.Delete() method 步骤2:如果文件已存在同名,则使用File.Delete()方法删除现有文件

Step 3: now copy the File into the new Location using File.Copy() method. 第3步:现在使用File.Copy()方法将文件复制到新位置。

Step 4: Rename the newly copied file. 第4步:重命名新复制的文件。

Try This: 尝试这个:

string NewFilePath = Path.Combine(NewFileLocation, fileName);
if(File.Exists(NewFilePath))
{ 
File.Delete(NewFilePath);
}

//Now copy the file first
File.Copy(FileLocation, NewFileLocation, true);

//Now Rename the File
File.Move(NewFilePath, Path.Combine(NewFileLocation, "File.txt")); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM