Our application requires a user to select a photograph from their camera. The cameras I tested with while adding this feature would all appear as a drive letter in "My Computer" so loading and working with the image was a no-brainer. A coworker gave me his camera which rather than mount as a drive it triggers the awful "Scanner and Camera Wizard". I was encouraged to see that in "My Computer" there was an entry for the camera and indeed I was able to browse to and select files from a standard OpenFileDialog. - GREAT!
Except that when I attempt to ACCESS the file I receive "UnauthorizedAccessException". Upon investigation I see that it's actually loading the files from this location:
C:\Documents and Settings\sk\Local Settings\Temporary Internet Files\Content.IE5\AXY0DNE3
What in the world?! IE5.5??
From here things keep going downhill. That location is apparently a very well hidden location that I can only navigate to by directly entering the path in the explorer bar. I then figured I could just copy the file to a temp location and work with it from there. So I did that but I still can't work with the file, throwing the same exception:
Access to the path 'C:\Documents and Settings\sk\Local Settings\Temp\IMG_0005[1].jpg' is denied.
It appears that the permission settings were copied along with the file (makes sense).
As a workaround I have instructed my users to use the terrible little wizard, copy the files to a temporary location and then select them fro there. I don't like this but I needed to get this feature deployed Today. With a workaround in place I would now like to try and get this working if possible. Ideally I could just work with the file without copying it around to other locations, etc. What I don't understand is why the UnauthorizedAccessException is being throw.
I'm hoping that someone out there has faced a similar challenge and can share some tips on how to work with these files. I'd rather not go the whole WIA route and work with the files via the camera interface.
The file is Read Only. I should have checked this!
Of course there are many ways to handle this. At first I thought "I will just force the read only attribute down" but then I thought "wait, I shouldn't need to do that, I am after all only READING the file" So long story short that made me look deep into my IO library and find that I wasn't explicitly setting FileAccess to Read like I should:
public static byte[] ReadWholeFileBytes(string filename)
{
Guard.ArgumentNotNullOrEmptyString(filename, "filename");
if(!File.Exists(filename))
{
throw new FileNotFoundException("Failed finding file " + filename);
}
using (Stream stream = new FileStream(filename, FileMode.Open, FileAccess.Read))
{
return ReadWholeStream(stream);
}
}
However for the sake of making this answer complete for others you can drop the Read Only with this little bit of code:
File.SetAttributes(openFile.FileName, FileAttributes.Normal);
Related
Currently I have been loading xml files based on user input from a textbox in a UWP app I am making. The app itself is designed to edit existing files while also display it (kind of like a text editor but only changing attributes and not the form of the file)
This all works fine for any file within my H drive (which I think is entirely local) but not from my C drive or any other network drive. Below is the section where I start loading the user's file at the very start of the application.
XmlTextReader reader = new XmlTextReader(fileAddress.Text);
XmlDocument doc = new XmlDocument();
try{
doc.Load(fileAddress.Text);
}
catch (System.UnauthorizedAccessException)
{
Debug.WriteLine("couldn't access file here");
}
Below is the error code I get without the catch with my C drive which is what I want to know how I can avoid (i.e. actually access the file)
Access to the path 'C:\Users\x\Documents\XML_Files\IEC_EI_AR_XMLDesign.xml' is denied.
Below is a path that does work (in my D drive) for the same file:
H:\XML_Files\IEC_EI_AR_XMLDesign.xml
I have looked into other posts and they don't seem to help or don't address this specific issue (certain drives working while certain drives not working). I tried these solutions here which seem pretty reasonable but they didn't work or were out of date
I need to save the XML file using linq with xml code in C#
I know that I might be needing to change the permissions of these folders or give Visual Studio/my program heightened permissions to let the user access their own drive though I am not quite sure where/how I could do this. Additionally, any solution I would still want to maintain read/write privileges.
Any advice or suggestions/referals are appreciated!
Found a workaround from the bottom comment of this answer UnauthorizedAccessException on writing XML to a file by saving/storing my files in "C:\Users<username>\AppData\Local\Packages<appname/ identifier>\LocalState"
This allows me to save/edit files in my C Drive (with user permission I guess) though I can now look into expanding these permissions to folders above this.
I have read a similar post, but i just cant figure out the problem.
I have changed the windows permissions and changed routes.
When i try to save a file it throws me the exception:
Access to the path **** denied.
string route="D:\\";
FileStream fs = new FileStream(route, FileMode.Create); <--here is the problem
StreamWriter write = new StreamWriter(fs);
patient person = new patient();
patient.name = textBox1.Text;
patient.name2 = textBox2.Text;
You are trying to create a FileStream object for a directory (folder). Specify a file name (e.g. #"D:\test.txt") and the error will go away.
By the way, I would suggest that you use the StreamWriter constructor that takes an Encoding as its second parameter, because otherwise you might be in for an unpleasant surprise when trying to read the saved file later (using StreamReader).
Did you try specifing some file name?
eg:
string route="D:\\somefilename.txt";
tl;dr version: Make sure you are not trying to open a file marked in the file system as Read-Only in Read/Write mode.
I have come across this error in my travels trying to read in an XML file.
I have found that in some circumstances (detailed below) this error would be generated for a file even though the path and file name are correct.
File details:
The path and file name are valid, the file exists
Both the service account and the logged in user have Full Control permissions to the file and the full path
The file is marked as Read-Only
It is running on Windows Server 2008 R2
The path to the file was using local drive letters, not UNC path
When trying to read the file programmatically, the following behavior was observed while running the exact same code:
When running as the logged in user, the file is read with no error
When running as the service account, trying to read the file generates the Access Is Denied error with no details
In order to fix this, I had to change the method call from the default (Opening as RW) to opening the file as RO. Once I made that one change, it stopped throwing an error.
I had this issue for longer than I would like to admit.
I simply just needed to run VS as an administrator, rookie mistake on my part...
Hope this helps someone <3
If your problem persist with all those answers, try to change the file attribute to:
File.SetAttributes(yourfile, FileAttributes.Normal);
You do not have permissions to access the file.
Please be sure whether you can access the file in that drive.
string route= #"E:\Sample.text";
FileStream fs = new FileStream(route, FileMode.Create);
You have to provide the file name to create.
Please try this, now you can create.
TLDR : On my end, it had something to do with AVAST ! => Whitelist your application.
All of a sudden, I also got this UnauthorizedAccessException problem in the windows WPF program I'm writing. None of the solutions worked - except I couldn't figure out how to elevate my application to full privileges (not using VS) while at the same time, being already on the administrator account, I didn't feel the need to dig that deep in permission concerns.
The files are image files (jpg, psd, webp, etc.) I wasn't trying to open/write a directory, it has always been a valid path to a file, and I needed to write to the file, FileAccess.ReadWrite was inevitable. The files (and any of their parent directory) were not readonly (I even checked by code prior calling new FileStream(path, mode, access, share) via FileInfo.IsReadOnly) - so what happenned all of a sudden ???
Thinking about : I had an had drive crash, so I unpacked a backup of my solution code from another drive. In the meantime, I added codes in my application to PInvoke APIs to directly read hard drive sectors physical bytes as well as USB plug/unplug monitoring.
I started to get the Exception when I added those, but even though I temporarly removed the related codes from the application, I still got the UnauthorizedAccessException.
Then I remembered one thing I've done long ago, a painstaking similar issue where I wanted my application to communicate sensible data via Wifi, which was to add the executable among AVAST exceptions, and the assembly directory aswell (My app was already among the authorized apps through firewall)
Just did it for my application in AVAST settings, AND THE EXCEPTION IS GONE !!! Two whole days I'm lurking StackOverflow and the web to get moving on, FINALLY !
Details : I can't pinpoint exactly what AVAST didn't like in my application as the only changes I made :
Retrieved then launched the backup code - it worked like a charm, files (images) opens/write without problems (3 days ago)
Added USB detection (3 days ago - Just tested the code, didn't tried to open an image)
Added PInvoke physical drive direct read (2 days ago - FileStream, and the logic to define where/how to scan the damaged drive - Just tested the code, didn't tried to open an image)
Added image format detection starting from Jpg/Jfif.. 2 days ago, got the exception upon testing the code.
While searching for solutions, added an Image Gallery WPF UserControl to diplay pictures based on their signature and check which files gives the exception : almost all of them (some files opens/write okay - why ???)
Tried everything I've found on SO (since the last 2 days) until I opened AVAST settings and whitelist my application.
... now I can move on into adding a bunch of file signatures to retrieve as many datas as I could.
If this may help those who like me, aren't failing on the "I'm passing a directory path instead that of a file", yet, have no time to learn exactly why antiviruses think our own code is a malware.
Just Using the below worked for me on OSX.
var path = "TempForTest";
I'm creating split archives using the following code:
string filename = "FileName.pdf";
using (ZipFile zip = new ZipFile())
{
zip.UseZip64WhenSaving = Zip64Option.Default;
zip.CompressionLevel = Ionic.Zlib.CompressionLevel.Default;
using (FileStream stream = new FileStream(temp, FileMode.Open))
{
zip.AddEntry(filename, stream);
zip.MaxOutputSegmentSize = settings.AttachmentSize * (1024 * 1024);
zip.Save(zipFileName);
}
}
The code above generates 3 files: file.zip, file.z01 and file.z02.
When I right-click that zip file and select Extract All (not using WinRAR or other zipping software to extract, just the built-in Windows zip) it gives me the following error:
The same volume can not be used as both the source and destination
What's weird is that it only happens on the first time I try to extract the files, the succeeding extractions are OK so it must be how the files were zipped in the first place.
UPDATE 1
The same thing happens even if I extract to a different folder
There have been discussions with regards to this issue on the DotNetZip Codeplex site, but it seems the issue has not been resolved yet
http://dotnetzip.codeplex.com/discussions/239172
http://dotnetzip.codeplex.com/discussions/371005
UPDATE 2
Looking at the doc for the MaxOutputSegmentSize property, it is quoted:
I don't believe Windows Explorer can extract a split archive.
There's no further explanation though as to why. I consider this to be a false-positive since as mentioned above,
it only happens on the first time I try to extract the files, the
succeeding extractions are OK
I'm using Windows 8.1 64-bit.
First thing you'd always want to do when searching for the reason why software fails is locating the source of the error message. You do that by using Google first. Second hit (right now) is golden, somebody has decompiled Windows executables and located this specific string as resource ID #10209 in a file named zipfldr.dll with a Microsoft copyright notification.
That is an excellent match, zipfldr.dll is the shell namespace extension that Windows uses to display the content of a .zip file as though it is a folder. You can see it in Regedit.exe, navigate to HKEY_CLASSES_ROOT\CLSID\ {E88DCCE0-B7B3-11d1-A9F0-00AA0060FA31} for the primary registration. The HKEY_CLASSES_ROOT\SystemFileAssociations\ .zip\CLSID registry key associates it with a .zip file.
So you have a hard fact, it really is the Explorer extension that falls over. Exceedingly little you can do about that of course. Only remaining doubt that it might be the Zip library you use that fumbles the spanned files content and thus causes the extension to fall over. That is significantly reduced by seeing more than one library tripping this error, the odds that both Ionic and Dotnetzip have the exact same bug is rather low. Not zero, programmers do tend to have a "how did they do that" peek at other programmer's code for inspiration. The fact that this error is spurious puts the nail in the coffin, you'd expect bad zip archive content to trip an error repeatedly.
You might be able to reverse-engineer the underlying problem, you'd do so with SysInternals' Process Monitor. You'll see Explorer reading and writing files. Probably in the TEMP directory, I speculate that you'd get an error like this one if a .zip file already exists in that directory. TEMP is a very messy folder on most machines, too many programs don't clean up properly after themselves. Including zip libraries, an attractive theory not otherwise backed-up by proof :)
If that doesn't pan out then the ultimate fallback is Microsoft. They have a 1-800 telephone number where you can get support for problems with their products. I've used it several times, they always solved my problem and refunded the upfront fee. This is a Windows problem however, a product that has a billion users. You'll, at best, get a workaround, an actual software fix is exceedingly unlikely. Not entirely impossible, it has been done. But very high odds that their recommended workaround is "use a 3rd party utility like Winzip". Not what you want to hear.
Please move the zip file to different folder or try to use 7zip to extract the files.
Download 7zip and Install it.
Move zip file to an other location.
Then, right click on the folder -> select 7zip -> Extract here
Nowadays I am dealing with a small application which updates the mssql's compact database files on an iss server.
I've preferred to use SSIS to organize the flow. For couple of days it worked well, but then started to give errors.
In SSIS I've used the "File System Task"s "Move File" operation to move generated files from a folder to iss server's shared folder. If it fails, in case of a locked file, it tries it later. But I've seen that sometimes the files in the destination folder started to disappear.
Then I've decided to write custom code. I've removed the "File System Task" and put a "Script Task" instead of it. And write a couple of lines in it.
string destinationFile, sourceFile;
destinationFile = Path.Combine(Dts.Variables["FileRemoteCopyLocation"].Value.ToString(), Dts.Variables["CreatedFileName"].Value.ToString());
sourceFile = Path.Combine(Dts.Variables["OrginalFilePath"].Value.ToString(), Dts.Variables["CreatedFileName"].Value.ToString());
bool written = false;
try
{
File.Copy(sourceFile, destinationFile, true);
File.Delete(sourceFile);
written = true;
}
catch(IOException) {
//log it
}
if (written)
Dts.TaskResult = (int)ScriptResults.Success;
else
Dts.TaskResult = (int)ScriptResults.Failure;
It worked well. But I tried it by locking the destination file. I've connected the destination file in Sql Server Management Studio (it is an sdf file). And surprizingly it works too.
And I've tried it from operating system, by copying the source file and pasting it to the destination. Windows 7 asks me if I want to overwrite it and I say yes and it overwrote the file (copy and replace) I use with another process, no warning no error.
But if try to rename or delete it does not let me to do that. Or if I try to cut and paste it (Move and Replace) it says "you need permission to do this action".
As I understood, "Copy, delete" and "Move" are totally different things. And I still can not understand how can I overwrite a locked file.
Any ideas?
File.Move method can be used to move the file from one path to another. This method works across disk volumes, and it does not throw an exception if the source and destination are the same.
You cannot use the Move method to overwrite an existing file. If you attempt to replace a file by moving a file of the same name into that directory, you get an IOException. To overcome this you can use the combination of Copy and Delete methods
Answer orignal from : Difference between in doing file copy/delete and Move
Although the subject is not new, I would like to share my experience. I had to change the pdf file names in my digital library. When I copied about 10,000 legal articles to another folder by changing their names using the File.Copy() method, half of it took about 15 minutes, and I stopped the process because of it takes so long. Then when I tried the same thing with the File.Move() method, the result was incredible for me: It took less than 1 minute to move the whole thing. Of course, I don't need to say that all these are directly related to the system features.
When I try to delete a file occurs the following exception:
The process cannot access the file ''
because it is being used by another
process.
My code looks like:
string[] files = Directory.GetFiles(#"C:\SEDocumentConverter\SOURCE");
foreach (string file in files)
{
File.Delete(file);
}
How can I solve this problem?
There is no way to delete a file that's currently being used by another process. You have to close whatever program has that file open first, before you can delete it.
If you don't already know which program that is, you can figure it out using Handle or Process Explorer.
You can P/Invoke the Windows MoveFileEx function, and use the MOVEFILE_DELAY_UNTIL_REBOOT flag, with a NULL destination name. This will delete the file when you reboot.
If the file is being used you're out of luck in trying to delete it. I can't tell you based on your code what process might be using the file(s), but try looking here or here or here, or at any of the other questions that show up as related to this one for guidance regarding this issue, and by all means follow the guidance from #Cody Gray about using Process Explorer.
slightly off topic: But it seems from your code that you are trying to delete all files of your folder.
Well instead of deleting them one by one we have another method Directory.Delete(path, True) which will delete the directory as contained in the string named path. Then you may recreate the directory if you want. But your problem may persist here too.
Another way is to find all open handles to the file and close them forcibly.
Works nice for you, bad for any apps which were using the file.
Could try that in UI with SysInternals ProcessExplorer.
Just rename this file. This will do the thing for whoever tries to write to that location.
Notes:
1) Of course the file is not deleted physically yet. Nice to do the MoveFileEx trick mentioned here around to complete the job.
2) If you want to delete a locked file to write smth new in its place (e.g. during build), just rename the file to a GUID name. If you need the folder to be clean, either use an ignored extension / hidden attribute, or rename the file to a path under %TEMP% (if on the same drive).
3) Not all locked files can be renamed, but it works for me for like 90% practical applications. You can move a file without affecting an open read/write/execute handle, it will continue working with the moved file just good (if moved within the same NTFS volume of course).
4) That's what Windows Installer would basically do before it asks you to please reboot somewhen soon: move the file away from your eyes, schedule to be removed upon reboot. Usually the newly-installed app can be used right away.
Practical Use:
My favorite is with MSBuild. Overriding the <Copy/> task with this stuff makes all the build go linux-way. You don't care if a prev version is still running somewhere, can still build&run. The old app keeps using the old version of the files. The new app loads the newly-written version.
Might be moving to %TEMP% if on the same drive (not my case though). I'd just rename them to an extension which is ignored with the current source control client.