I just wanted to see if anyone else got this issue.
I am trying to copy files from one directory to another, however when it gets to a file copy such as this:
//copy each file
foreach (var file in Directory.GetFiles(sourceDir))
File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)), true);
It gives me an error such as "DirectoryNotFound" Exception. Even though the directory exists.
Has anyone run into this problem and what would a good solution around it be?
Thanks
Related
I have the following piece of code in a .NET 6 app that copies some files to a different destination on the file system:
DirectoryInfo targetDir = GetTargetDir();
foreach (FileInfo fi in GetFilesToCopy())
{
fi.CopyTo(Path.Combine(targetDir.FullName, fi.Name), true);
}
As you can see, I'm passing true to the .CopyTo() method, so it overwrites the file if it already exists.
However, this seems to not work properly:
If the destination file does NOT exist, the copy works fine
If the destination file DOES exist, however, the copy operation fails and throws a UnauthorizedAccessException with an error message like 'Access to the path 'C:\my destination dir\my destination file.ext' is denied.'
I've checked the method documentation, and it says that that exception is thrown if the destination is a directory or if we're trying to copy to a different drive. However, I'm not doing any of those things (and anyway it doesn't explain why it works if the file does not exist)
I've checked all I could think of, and it all seems in order:
The user running the application has permission to write to that location and is the owner of the existing files
The files are not in use, I can easily delete them using windows explorer or cmd
I've also tried running the code as administrator (even though it shouldn't be needed) but same error occurs
Can anyone tell me why this is happening?
Apparently the problem was the files have the Read Only attribute (thanks to #nilsK for pointing me in the right direction).
I've resolved this with the following code:
string destFile = Path.Combine(targetDir.FullName, fi.Name);
if (File.Exists(destFile))
{
File.SetAttributes(destFile, FileAttributes.Normal);
}
fi.CopyTo(destFile, true);
I have a problem very curiosity.
I am delete files into folders this is the algoritm
System.IO.DirectoryInfo di = new DirectoryInfo(folderPath);
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo dir in di.GetDirectories())
{
dir.Delete(true);
}
I choose the directory and the algorithm deletes: folders, subfolders and everything related without problem.
The problem occurs when I download a compressed file, which has folders and subfolders (it is important to mention, that the data in the compressed file is what I should actually delete).
and the software reports an error: Access denied
The truth is that I do not understand, the files of that compressed (.zip) specifically some folders of that compressed file are the ones that will not let me delete.
Is there something missing in the algorithm that allows deletion?
At first, to recursively delete folder with all files and subfolders you can just call Directory.Delete(folderPath, true).
As described in documentation, you can have UnauthorizedAccessException if file or folder is protected. One of solutions you can do is to require your application to launch with admin privilegies as described in answer https://stackoverflow.com/a/2818776/10115818
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.
So I've been working on a new programm right now and I'm stuck at one function and I don't know how to solve this problem.
So I'm trying to make a button which searches and prints paths of files and folders which have a specific name. After I tried some functions and they all failed, I found this and it should work but it just doesn't print anything.
string[] files = Directory.GetFiles(#"C:\Program Files", "NameOfFileOrFolder",
SearchOption.AllDirectories);
foreach (var file in files)
{
Console.WriteLine(file);
}
Btw. the console does not even open itself...
You can try to read this: https://msdn.microsoft.com/en-us/library/ms143316(v=vs.110).aspx
Also you need administrator's privilege for using current path.
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?