Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
718 views
in Technique[技术] by (71.8m points)

c# - File.Move Does Not Work - File Already Exists

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...