问题
I'm using Directory.Move(oldDir, newDir)
to rename a directory. Every now and then I get a IOException
saying "Access to the path "oldDir" is denied". However if I right click the directory in the explorer I can rename it without any issues. How's that and how can I get it to work?
EDIT
The program is still running, I get the exception and can rename it manually while my cursor is paused on the breakpoint. I also tried setting a breakpoint at Directory.Move
, successfully renamed the directory in explorer (and back again), stepped over Directory.Move
and ended up in the catch (IOException)
again. So I don't see why my program should lock the directory at all. There must be something else.
Any ideas?
EDIT 2
Here is my code
public bool Copy()
{
string destPathRelease = ThisUser.DestPath + "\\Release";
if (Directory.Exists(destPathRelease))
{
try
{
string newPath = ThisUser.DestPath + '\\' + (string.IsNullOrEmpty(currBuildLabel) ? ("Release" + '_' + DateTime.Now.ToString("yyyyMMdd_HHmmss")) : currBranchName) + '.' + currBuildLabel;
Directory.Move(destPathRelease, newPath);
catch (IOException)
{
// Breakpoint
}
}
}
}
As you can see I just entered the method. I never touched the directory in my program before. Is there another way to rename a directory?
回答1:
Without seeing more code I'd say your application is locking a file within the directory, you can see what is accessing the directory using Process explorer
from the intro to process explorer:
Ever wondered which program has a particular file or directory open? Now you can find out. Process Explorer shows you information about which handles and DLLs processes have opened or loaded.
It might also be worth making sure nothing else is copying files from/to that directory - e.g. dropbox. I had an issue recently where visual studio would stop debugging because of a file lock - in the end it was indexing on the drive which was temporarily locking the file. Process explorer only partially helped in that it showed 'system' had the file lock and not another application.
回答2:
You need to check the User that is running the .net application. It don't have the right permission to execute the rename.
This is:
- the user running the application pool for web applications
- the logged application for console/winforms application
- the configured user for services or scheduled tasks
回答3:
If the parent directory of your destination directory does not exist, The Directory.Move
operation with fail. I've just been trying to figure out something loosely similar to this.
来源:https://stackoverflow.com/questions/16280310/cant-rename-directory-in-c-sharp-but-manually