Directory Rename Exception in C# - c#

When I try to rename a Directory using the following code:
try
{
System.IO.Directory.Move(oldPath, newPath);
}
catch (System.IO.IOException e2)
{
Console.WriteLine(e2.Message);
}
I get the following exception: The process cannot access the file because it is being used by another process.
I don't understand why it says "file" in the first place.
Also, the directory is empty. What file is it referring to?
Lastly, how to manage to rename the Directory without any exceptions?
UPDATE: I guess I found the reason for the exception, it is because I am trying to rename the file/folder names of files/folders situated in the Google Drive. The Google Drive application is the other process using it! Any solutions to rename a folder in the Google Drive? But the weird thing is that I don't get this exception when I try to rename files located in the Google Drive through C#.
Thanks!

Your folder seems to be in use by another process. Try to close your explorer or other programs, that use that folder. If nothing help - try to restart your machine. If those won't help - consider using Unlocker to free folder from usage of another process. Note that it would be weird, if non-system folder is occupied after restart of the machine

It says "file" because the underlying commands are probably using a
generic move command for both directories and files and the
localized error string contains the word file.
Even if a directory is empty, it can be locked for any edits if you have it "open" in an application (do you have explorer Windows open in the directory, is the command prompt current directory set to the one you want to move/delete)?
Unfortunately there's not much you can do unless you want to start killing offending processes programmatically.
You can use Process Explorer to find the process that has a lock on that folder. See http://windowsxp.mvps.org/processlock.htm for more info.

1 Verify that newPath already does not exist
http://msdn.microsoft.com/en-us/library/system.io.directory.move.aspx
2 Verify that your directory does not contain opened file

Related

C# Directory.GetDirectories() return inexisting directory

I want to use Directory.GetDirectories(path) and then working with sub-directories but, when I start running my app, VS return me System.UnauthorizedAccessException. I can understand I fix this, no problem. The real problem is, as you can see in the linked picture, code try to acces a folder that doesn't exist.
In windows explorer I show all hide files and folder, and as you can see (again) when I go to the right spot in my PC, "Ma Musique" doesn't exist (and never existed by the way).
Where is folder come from and how can I deal with this ?
EDIT :
Code try to access this directory just after Lumion directory. As you see above, "Ma Musique" doesn't exist.
CMD (as administrator) doesn't find it too.
Directory.Exists() return true when give it "Ma musique" directory path.
That is what is known as a "virtual" folder and it is there for backwards compatibility with old versions of Windows. When users got their own music/video/etc folders, they were all turned into system virtual folders that don't actually exist at all as they are aggregates of content in multiple folders. However programs that expect these folders to exist would break if they were missing so Windows would make a symbolic link that in some cases would allow a redirect. I don't remember for sure but i think the redirect only worked if you were running as administrator. In any case you can't browse into them as they aren't real.
You are seeing "acces denied" and/or do get this Exception "System.UnauthorizedAccessException".
Microsoft has a tool ICACLS that displays or modifies discretionary access control lists (DACLs) on specified files, and applies stored DACLs to files in specified directories.
Because of the mentioned error, you should investigate the response of:
icacls "C:\Users\thoma\Documents\Ma musique"
(When you get an error about "Access denied", please execute this as Administrator)
The output of ICACLS should explain why you do no have access to that file/directory.

Could not find a part of the path with network path

I'm basically creating a directory in MyDocuments. I think it's worth mentioning that MyDocuments at my company is a network path.
var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
path = Path.Combine(path, string.Format(#"A\XXX\C\{0:yyyyMMdd_HHmmss}", startTime));
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
The issue here is quite funny. It was working fine for 2 years and recently I cleaned manually path in subdirectory 'XXX'. Now it doesn't work. If I change 'XXX' to anything else it works. It looks like something is wrong with this particular directory. I can delete that directory manually and recreate it in windows explorer. It happens when running from VS2015 and from exec as well. Any ideas?
Edit:
Just to clarify:
Exception thrown: "Could not find a part of the path"
In Line Directory.CreateDirectory(path);
Edit:
The reproduce in windows explorer:
I can create and remove XXX and C this is fine. When I tried to create any subdirectory in C windows explorer hangs. So I removed the entire A directory and now when I try to create it manually I can't recreate A because it says that the folder or a file in it is open in another program. How is it possible if it doesn't exist.
The answer is pretty simple. In your company we use sync center to synchronize data on this shared drive. The root directory wasn't fully synchronized so whenever I tried to create directory it thrown an error. After synchronizing and deleting it from my mirrored version and sync center version I could create it again.

Deleting a directory, recreating it, and adding files to it

My issue is this. I was creating a directory and filing it with files for running a specific process and on subsequent runs it would delete the directory, recreate it and start filling it with files.
root\scripts\'Many files'
All this code seemed to run fine without errors until I opened up my Windows Explorer window and navigated into the 'scripts' directory. When I would run it again it would kick me out of the folder as expected when it deleted, but it would throw an exception trying to add files to the directory, and when I looked the 'scripts' directory didn't even exits.
DirectoryNotFoundException was caught: Could not find a part of the path
My Code looked like this.
if (Directory.Exists(scriptsDirectory))
Directory.Delete(scriptsDirectory, true);
Directory.Create(scriptsDirectory));
File.WriteAllText(scriptsDirectory + fileName, output);
I looked on the internet and found this: Windows Explorer and Directory.Delete()
It seems there's something odd with Windows Explorer, but my issue was different. It wouldn't throw an exception on delete, but when I was trying to add files to the directory, b/c the createDirectory didn't seem to fire while I was in the directory.
My solution is below.
My solution was instead of Deleting the Directory, I instead deleted all the files from the directory, and that worked for me.
if (Directory.Exists(strScriptsDirectory))
{
DirectoryInfo directoryInfo = new DirectoryInfo(strScriptsDirectory);
// Delete the files
foreach (FileInfo fileInfo in directoryInfo.GetFiles())
fileInfo.Delete();
// Delete the directories here if you need to.
}
else
Directory.CreateDirectory(strScriptsDirectory);
This fix might not work well for all solutions and the solution provided in the link doesn't seem too great.
Another solution we tired was too write a while (true) loop that had a try catch to try to create the directory and add a file to it (if the add file caused an exception it would be caught and try again) and if it succeeded it would delete the test file and break out of the while.
Does anyone have any cleaner solutions that would allow you to delete a directory and recreate without having to worry about if a user is within an Explorer window?

File.Copy fails when copying a DLL that is not in use

I've built a winforms app (C#) that will take a list of file paths, and copy those files (from a different VS solution) to a new location (In a folder the user specifies) in the same directory structure they currently exist on local file system.
I use the Path class, Directory class etc and everything works wonderfully...except when it reaches a file path that points to a DLL.
The DLLs I am trying to copy are a part of the other solution, and that solution is not currently open.
I have tried restarting computer to make sure visual studio isn't somehow hooking into that DLL even after the solution is closed.
The DLL in question can be copied by regular manual means (i.e. copy and paste shortcut).
So short of creating a batch file in the program, and running xcopy on that DLL path, I don't know of a way to get this to work.
From what I have found from google searches (which isn't much on this particular situation), File.Copy() should work..
Any help would be wonderful, even if it is a link to a duplicate question I may have over looked.
Thanks!
-The error message is: The process cannot access the file [insert file path] because it is being used by another process (The path is definitely correct also)
-Just downloaded and tried to search for the DLL name with Process Explorer.. I also ran a similar exe from command prompt to no avail. It claims nothing is using it. That's why I am utterly baffled by this. Also, I just checked the permissions and everything looks great (i.e. Full Control, owner effective permissions)
-It does not handle open files. It basically build the correct src and dest paths and does a File.Copy() on those. How would I go about handling open files? I'm sure I could figure out if it was open, but what would I do it it were open?
It is not complaining about the file you're trying to copy, it is complaining about the file that you're trying to overwrite with the copy. Lots of candidates for that, virus scanners always get very excited about new DLLs, for example. Or it is loaded into a process, the typical failure mode for trying to implement your own auto-updater.
You can rename the target file to make your copy succeed.
Are you in vista or win7? If so, Check your 'User Account Control Settings'. Sometimes this can interfere with .NET security options and prevent file operations that would otherwise work.
As well as Process Explorer, I would use Process Monitor also from Microsoft so you can see what is happening at the point of failure and allows you to see if anything else is accessing the dll.
Possible culprits are
the program you are running,
your antivirus package
a virus.
If the path it is complaining about is the destination path, then is is possible that the path is too long?
Also, when using Process Explorer, make sure you have enabled the option to show details for all processes and not just your own.
I just ran into this issue as well. I tried copying a .DLL from an FTP server to a local directory (replacing the existing one) and for the life of me I could not get it to work. Keeps giving me an 'Access Denied code: 5' Error.
I then realized that the .DLL on the FTP server was not marked as hidden while the .DLL I was trying to replace was marked as hidden.
Once I changed the local one to also be visible. I had no more issues.
So my solution is:
Make sure both files are visible.
Hope this helps someone

Prevent Windows Explorer from interfering with Directory operations

Sometimes, no "foo" directory is left after running this code:
string folder = Path.Combine(Path.GetTempPath(), "foo");
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
Process.Start(#"c:\windows\explorer.exe", folder);
Thread.Sleep(TimeSpan.FromSeconds(5));
Directory.Delete(folder, false);
Directory.CreateDirectory(folder);
It seems Windows Explorer keeps a reference to the folder, so the last CreateDirectory has nothing to do, but then the original folder is deleted. How can I fix the code?
EDIT:
I'm sorry that my question wasn't clear. My objective is to create an empty "foo" directory. If the directory already exists, I delete it and create it anew. The problem is that if Windows Explorer is looking at the directory, the CreateDirectory call sometimes fails silently. No exception is raised; the directory just isn't created.
The code above reproduces the issue in my computer. Only the last two lines belong to my actual application. The previous lines are setup. After you run the code, does "foo" always exist? This is not the case half the time in my pc.
For the time being, I'm manually deleting each file and subdirectory of foo.
Since you did not provide details (like exceptions, errors), I will assume this is the problem.
I think the problem is that the explorer is still running when you run the command to delete the folder. This could be a locking problem.
Directory.Delete(folder, false);
Either that, or there is some other application accessing that folder or its sub-folders or files, if any by chance.
I would recommend not touching the folder via explorer or any other app, if possible, and wait for the explorer to exit first, before deleting the folder.
Process p = Process.Start(#"c:\windows\explorer.exe", folder);
Thread.Sleep(TimeSpan.FromSeconds(5));
p.WaitForExit(); //<-------
Directory.Delete(folder, false);
Also, please do not ignore the exceptions and errors thrown and paste them here, if any.
Hope it helps.

Categories

Resources