Split PDF and save but Access is denied [duplicate] - c#

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";

Related

Getting UnauthorizedAccessException when acessing a Xml file via the .load method C#

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.

Reading a file opened from "Scanners and Cameras" throws UnauthorizedAccessException

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);

C# Cannot write to Application.ExecutablePath, some boxes i can some i cannot? uninstall from this

So I have been writing to
Environment.SpecialFolder.ApplicationData
this data file, that upon uninstall needs to be deleted. I am using Innos Setup to build my installer. It works great for me. So my data file hangs out in the above path and I do that cause when I used to try to write it to
Application.ExecutablePath
certain boxes I tested it on would throw a nasty error at me trying to write data there. I do research and somehow its not always writable and its how i came up with the Environment.SpecialFolder.ApplicationData
That is why my data file now resides in the SpecialFolder.ApplicationData. Trouble is if the user uninstalls and reinstalls I need that file gone. It might be a short coming of my knowledge of Innos but I cannot figure out how to know where that file will be to tell innos that.
So then I thought I had a clever solution: Innos can run a file when its done uninstalling, so I had my program create this file "uninstallData.bat" that says:
del "the file in my special folder application data path"
and I wrote it out to drumroll
Application.ExecutablePath
(yes it was a while in development and I had forgot it was't doable.)
So of course I am back to square one, I need to write a file to a path Innos knows about {app} and I need it to be able to delete my data file in the SpecialFolder... i don't care how I do it i just need that file gone.
Are there other Environment. or Application. approches I have missed? Maybe somewhere that is viewable by an uninstaller AND can be written to?
As an aside, I am not sure why my box I develop on can write to the application folder no issue, but it cannot on other boxes... weird.
Any input would be great sorta lost as to how to crack this nut.
The environment location is in the user profile. If there are multiple users on the machine, and they all run the application then a copy of the file will be in each profile.
The path also depends on the OS.
Regardless, the current user's app data location is pointed to by %APPDATA% and %LOCALAPPDATA%. These Windows environment variables should be available within Innos.
Appliccation.ExecutablePath is not writable per standard defintions - the program files folder should never be manipulated by running applications. Ther area number of special folders for that. Nice that you finally found.... what is properly documented by Microsoft for a LONG time now (minimum 10 years).
I suggest you get a proper installer - WIX comes to my mind. Your problem is totally unrelated to C# - it seems to be totally a "crappy installer" issue. Or provide a PROGRAM (not bat file) to run at uninstall. What exatly is your problem there?

Need to find a way to programmatically delete undeleteable empty folders

I've got a large folder on an offsite backup machine that gets populated with files by rsync (through deltacopy) every night (running windows xp) from the main work site. I've discovered some annoying folders that cannot be opened, or deleted, or even checked for file sizes. I get the such and such a folder is not accessible, access is denied message when I try to click on it in windows explorer. According to the windows explorer tooltip they are also "empty" and the properties of these folders say 0 bytes and 0 files.
I currently have a C# program that goes through every folder and file and tries to copy the whole backup directory to a dated backup-backup directory, which is how i discovered this problem in the first place. The regular System.IO library seems helpless against these blasted folders. Exceptions are thrown when I even try to access the folder path.
Does anyone have any clue how I could, say, on an access denied exception in my existing copy code, force the delete of these folders so rysnc can recreate the directory again and get the whole thing synced again?
First thing I think of when I see this is time to do a checkdisk. From the sounds of it, it feels more like a file system problem than something solvable the way you want to go about it.
Yes, try the awesome "Process Explorer" from Microsoft (formerly SysInternals).
Although it's for the processes in the windows filesystem, you could search for your folder in the explorer window & it will tell you who is locking it.
Once you release the process, your program would be able to delete the folder.
If that doesn't work, see if you can specify additional parameters to bruteforce the delete in your program.
It sounds like the filenames are either bad or contain characters that are invalid in Win32. Did you try to delete the directories with rd /r? Did you do a dir /x on them and try to delete the files/directories using their short names?
I would say that you first have to figure out why you can't delete the folders. Once you figure that out, you can write a program to fix it.
OK, so now that you know it's a permissions problem, the first step is to take ownership of the files (so you can set the permissions), then change the permissions so that you can delete the files.
Here's code to take ownership of a file:
WindowsIdentity currentUser = System.Security.Principal.WindowsIdentity.GetCurrent();
FileSecurity acl = File.GetAccessControl(filename);
acl.SetOwner(currentUser.User);
File.SetAccessControl(filename, security);
The trouble was that SYSTEM owned these files. I set deltacopy to run as administrator so that administrator would own the files deltacopy makes.
I guess windows is doing its job. The permissions are airtight. But if this happens again someday where I'd have to grab ownership from some other user to the current user (who has administrator permissions) how would I do that in code?
A question for another day I suppose. Thanks again everyone.

Where to store custom configuration files

I currently store a serialized XML file in the application directory that contains all changes specific to the program operation (not typical system or user configuration). Weeks ago, we started running into problems where it would not save correctly (read my previous question about this).
Long story short, we finally discovered that Windows 7 (and sometimes Vista) has an issue with writing into the application directory (specifically anything under Program Files). Now, if this were a normal configuration file I would simply store it under the user's APPDATA folder, but it is not normal. We run this on our own instrumentation, and misconfigurations are 99% of the reason customers have issues running our software. So we need this file to be accessible such that they can easily find it and email it to us. Appdata is hard enough for experienced users to find, much less very non-technological people.
We've also tried running it as Administrator, and making folder permissions wide open (we have control over every computer it runs on; it will never run on some random person's machine). But, these sometimes work, and sometimes do not.
The worst part is that when I write the file back out, it doesn't even throw an error; it simply writes it to some temporary directory that expires at some unknown point in time. Weeks later, our user will have an issue, and the configuration file is all messed up.
So, my question is where should I be storing this file, if not in Program Files? Should I just put it in APPDATA anyway, and make a small utility that emails it to us automatically in case of a problem? Or can I leave it in Program Files, but change some specific permission or registry key to allow it to operate normally?
It depends on whether or not the user needs to edit the file directly. If not, you should put them in %APPDATA%, which you can access via:
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
Otherwise, you might put it in My Documents:
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
Either way, putting it in Program Files is not a good idea. As you discovered, there are permission issues, even if running as Administrator.
For those users, you could build a button in that would open this directory. You could put it in an inconspicuous place that you could later direct them to.
For users that have an email client on their box, you could have a button that would create a new email with subject and automatically attach the file to the email.

Categories

Resources