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

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

Related

Could not write to output file -- Access is denied

I recently switched computers and copied all my projects over to my new local drive. I reformatted the computer I'm on now so it was pretty much a clean machine. Everything seemed to be working fine, but when I opened one of my projects that I had been running from my old machine, it would no longer compile, and I get the following error message:
Could not write to output file 'c:\Users\user\Documents\Projects\RegressionWeb\OnetouchUpload\obj\debug\OneTouchUpload.dll' -- 'Access is denied.'
I'm getting an error like that for each project I have in my solution. I'm also getting this error:
Unexpected error creating debug information file 'c:\Users\user\documents\projects\RegressionWeb\RegressionWeb\obj\Debug\RegressionWeb.PDB' Access is denied
I've searched high and low, and the only similar issues I could find online related specifically to ASP.NET and IIS, neither of which has anything to do with my project (My projects are class libraries of mostly NUnit tests with some support classes).
I am the administrator on my local machine. I have already taken ownership of every file in the project using takeown /f .\RegressionWeb /r /d y and also tried to ensure that nothing had a status of Read-only, but the following file threw an error when I tried changing the read-only property of it's parent folder:
An error occurred applying attributes to the file:
C:...\Regressionweb.sln.DotSettings.user
Access is denied
Basically this project was working perfectly and had no errors from my old computer. After copying over everything, this DotSettings.user file will not be modified, and Visual Studio can't write to any of the dll files. I'm sure the answer must lie in a Visual Studio setting somewhere. Any and all suggestions would be greatly appreciated.
I think Karl has it right. I had a similar situation once, and what I did was delete the file in question, clean the solution, and then rebuild. If the project needs that file it should recreate it; in my case it didn't need it because it never recreated it, but the project ran just fine.
One other thing I would recommend; you may be selecting the read-only attribute of the parent folder off and selecting this setting to recurse through all sub-folders and files, but that doesn't mean that's what's happening. For all your sub-folders and files (especially the ones that are cropping up as errors) inspect each one individually and make sure the read-only attribute is off.
My money is on your files are read-only. Verify they are read-only and change them or add your files to a source control system and let them get handled by that.
I was able to get this working by closing Visual Studio and then opening it again, but being careful to run Visual Studio "As Administrator". To do this, from the Start menu, right click on Visual Studio and choose "Run as Administrator".
it seems that the same error is sometimes displayed when the app pool user doesn't have access to the %TMP%/%TEMP% folder.
You'll need to grant IIS_IUSRS read and modify access over the temp folder of the user the app pool is running as.
This could either be the temp folder in the app pool user's profile, e.g. c:\Windows\ServiceProfiles\NetworkService\AppData\Local\Temp, or the system temp folder at c:\windows\temp.
See if it is related to this:Could not write to output file - Access is denied
. That would be a bit of a bugger to track down. In this case the project is self-referencing the dll and preventing access to the file.
This has a very simple solution, you just have to make sure that your directory name(folder name) is not the same as your file name. I created a folder by the name Pointers, my code was in a file pointers.cpp. When I compiled the code it kept showing the same error. I just had to change the directory or folder name to L1_pointers. You can change it to anything you want and it worked.

Failed to load a dll in the Temp Directory on a Windows Server

I have developed an C# application that run very well in local.
But there is a problem when i put on the server.
The application use a DLL library (A.dll) in a point of the execution, this A.dll copy (or is create at the first execution) another DLL (B.dll) in the AppData/Local/TEMP directory. But when the A.dll try to load the B.dll an exception is threw:
system.invalidoperationexception: failed to load B.dll
I have tried to run as Administrator the main exe, but with no results. And i think that the permissions are ok, after all is the TEMP directory.
I have not access at the DLLs source, are libraries.
Anyone can suggest me any solution? Would i check better? Where?
Thank You All.
Have you checked that the system does not restrict execution of code from within the temp directory, e.g. using SRP or AppLocker?
This is usually set in group policy and is generally a sensible restriction these days to prevent things such as drive-by installers and cryptolocker malware.
You can verify this by trying to run an executable from %TEMP% and seeing if you get an access denied error.
If this is the case you can try relocating TEMP (as SRP usually defaults to locking you out of %USERPROFILE%\AppData\Local\Temp and moving the Temp folder will have the desired effect.
Hope this helps!

Image.Save to relative path doesn't save where expected

The documentation doesn't explain the behavior when passing in a path such as "myFile_temp.jpg" but I would assume that it would save the the application directory because this is a relative path, relative to the application we are currently running.
I think that the problem can be solved by prepending the current application directory to my temp file name using
string appPath = Path.GetDirectoryName(Application.ExecutablePath);
Sure there are lots of ways to do it, but this should work.
My issue is I'd like to know why this is happening rather than just throw a patch on it and ship it back out to the users.
Code is WPF, C# project compiled with .NET 4.0 and Visual Studio 2010 and runs on a lot of different machines. Mostly 32-bit XP,while the dev machine is a 64-bit Windows 7.
Can any one explain this behavior and why it's occuring?
Edit
The files will on occasion be saved to the directory the user selected files from to manipulate. They resize them, the program keeps track of the size percent for each of the file paths. When the user is finished they will click done and the program will go through each of the file paths, create a copy, resize the image and then save it with a _temp on the end.
Take note that it doesn't always do it and it when it does it doesn't do it for all the files they touched.
It works as s expected. You just didn't expect valid behavior. Lets assume that your app is placed in c:/superapps/myapp.exe. You opened command line and you're in C:\ which means that this your current working directory.
You can still run your app by ./superapps/myapp but your working directory is still C:\. And this will be working directory of your app in this case, not the directory you placed the binaries.
That is why it may not have permission or save data in some unexpected by you location. You should always think that your app could be run just like any other command like dir. It will be working in the place where user is currently standing (his current working dir) not in the place it's binaries are stored in

File redirection from Program data to AppData\Local\VirtualStore\ProgramData

I am using C# with .net 3.5
I am saving my program data in a file under: C:\Program Data\MyProgramName\fileName.xml
After installing and running my application one time I uninstalled it (during uninstallation I'm removing all the files from "program data")
and then I reinstall the application, and ran it.
The strange thig is that my application started as if the files in program data existed - means, I had old data in my app even though the data file was deleted.
When running:
File.Exists("C:\Program Data\MyProgramName\fileName.xml")
I got "true" even though I knew for sure that the file does not exist.
The thing became stranger when I ran the application as admin and then the file didn't exist.
After a research, I found out that when running my application with no admin priviliges instead of getting: "C:\Program Data\MyProgramName\fileName.xml" I get "C:\Users\userName\AppData\Local\VirtualStore\ProgramData\MyProgramName\fileName.xml"
and indeed there was a file that existed from the previous installation (that I obviously didn't delete ,because I didn't know it existed).
So apparentlly there is some virtual path to the file under program data.
EDIT :
I found out that after deleting the old file in the virtual store, my application is suddenly able to find the correct file. (I didn't make any changes in the file under Program Data.
My question is:
why is it happen.
How can I prevent it from happening
Thanks in advance
Do you actually have to write to the per-system Program Data folder instead of the per-user Application Data folder(s)?
You might want to take a look at Environment.GetFolderPath and the following Environment.SpecialFolders:
Environment.SpecialFolder.ApplicationData - data folder for application data, synchronized onto domain controller if the user profile is roaming
Environment.SpecialFolder.LocalApplicationData - data folder for application data, local and not synchronized (useful for, for instance, caches)
EDIT:
Tested on Windows 7 x64, non-administrator user.
var appData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
var myFolder = Path.Combine(appData, "MyApp");
if(!Directory.Exists(myFolder)) Directory.CreateDirectory(myFolder);
File.WriteAllText(Path.Combine(myFolder, "Test.txt"), "Test.");
This does what is expected, ie. writes into C:\ProgramData\MyApp\Test.txt. As far as I can tell (Administrator mode Command Prompt), there's no UAC virtualization going on either.
Double edit:
I guess what's happened is that at some point an Administrator user has written the files into your ProgramData folder, and as such, UAC file system virtualization kicks in and redirects the non-administrator writes into the VirtualStore.
Does your uninstaller run as Administrator? If it does, you might have to check both the VirtualStore path for the user who initiates the uninstall, and the actual file system path for program data to remove. I'm not sure if there's an official way to do this, though...
I found the reason for the bug.
the application is trying to take ownership on the file and then the other file is created.
I removed that line and now everything works just fine.

How to write files in c# as an administrator?

I have c# program which writes an xml file to "C:" disk. I published my program as one click package because it's for test purpose only. But the problem is the one click package doesn't have "run as admin" option. So how can I solve this problem ? Any idea ?
The correct solution is not to force administrator elevation to bypass the built-in operating system security.
The correct solution is to fix the broken program. Even though it's just a test program, it should be written correctly.
See this SO question and the answers for more details. Even though it deals with the Program Files folder instead of the root, the underlying problem and solutions are identical.
I don't know if this works with One Click Deployment, but you could try to include an Manifest with your executable to request that the application is run with higher privileges.
See Create and Embed an Application Manifest (UAC).

Categories

Resources