Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I've got a folder:

c:est

I'm trying this code:

File.Move(@"c:estSomeFile.txt", @"c:estTest");

I get exception:

File already exists

The output directory definitely exists and the input file is there.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
732 views
Welcome To Ask or Share your Answers For Others

1 Answer

What you need is:

if (!File.Exists(@"c:estTestSomeFile.txt")) {
    File.Move(@"c:estSomeFile.txt", @"c:estTestSomeFile.txt");
}

or

if (File.Exists(@"c:estTestSomeFile.txt")) {
    File.Delete(@"c:estTestSomeFile.txt");
}
File.Move(@"c:estSomeFile.txt", @"c:estTestSomeFile.txt");

This will either:

  • If the file doesn't exist at the destination location, successfully move the file, or;
  • If the file does exist at the destination location, delete it, then move the file.

Edit: I should clarify my answer, even though it's the most upvoted! The second parameter of File.Move should be the destination file - not a folder. You are specifying the second parameter as the destination folder, not the destination filename - which is what File.Move requires. So, your second parameter should be c:estTestSomeFile.txt.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...