Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot create a file when it already exists using File.Move

Tags:

c#

I was trying to move a file from my Resx to my PC, but I'm keep having problems.

So I import a folder named "bad" in the Resources and I use the File.Move method to move the folder "bad" into my PC. But the program keeps crashing because it says: Cannot create a file when its already exists.

Here the code I use:

//txtpath is the root folder. I let the user choose the root folder and save it in txtpath.text

private void btnbadname_Click(object sender, EventArgs e)
{
        string source = "Resources\bad";
        string destination = txtpath.Text + @"\RADS\projects\lol_air_client\releases\0.0.1.74\deploy\assets\locale\App";

        File.Move(source, destination);

        MessageBox.Show("脏话ID已开启, 教程请点击下面的链接");
}
like image 785
Rain Avatar asked Mar 06 '14 15:03

Rain


3 Answers

The destination Directory cannot exist. In your code you are creating the Directory if it doesn't exist and then trying to move your directory, the Move Method will create the directory for you. If the Directory already exists you will need to Delete it or Move it.

See: Cannot create a file when that file already exists when using Directory.Move

like image 91
Tony Avatar answered Oct 24 '22 21:10

Tony


Destination supposed to have the filename as well

string destination = txtpath.Text + @"\RADS\projects\lol_air_client\releases\0.0.1.74\deploy\assets\locale\App\yourfilename.ext";
like image 22
Jude Avatar answered Oct 24 '22 21:10

Jude


You are using File.Move to move directory, why not using Directory.Move.

The MSDN documentation will only move files from a source to a destination, while Directory.Move will move the directory itself.

If I misunderstood you, and you want to move a file;

You can check if the file exists before or not using something like:

if(File.Exists(fileName))
    File.Delete(fileName);

Edit: If you want to iterate through the directory and make sure that the file doesn't exist before moving it, you can use something like:

//Set the location of your directories                
string sourceDirectory = @"";
string destDirectory = @"";

//Check if the directory exists, and if not create it
if (!Directory.Exists(destDirectory))
    Directory.CreateDirectory(destDirectory);

DirectoryInfo sourceDirInfo = new DirectoryInfo(sourceDirectory);
//Iterate through directory and check the existance of each file
foreach (FileInfo sourceFileInfo in sourceDirInfo.GetFiles())
{
    string fileName = sourceFileInfo.Name;
    string destFile = Path.Combine(destDirectory, fileName);
    if (File.Exists(destFile))
        File.Delete(destFile);

    //Finally move the file    
    File.Move(sourceFileInfo.FullName, destFile);
}
like image 42
CodingMate Avatar answered Oct 24 '22 21:10

CodingMate