Unauthorisedaccessexception - how to gain access? - c#

I have a winform application to compress and move some files. When I try to access a path on my desktop, I get an unauthorisedaccess exception. I am running visual studio as administrator (says that in the program bar) and I am a full admin on my machine (can access other accounts, etc).
How can I acess this path (folder)? One of the problems I have is the folder keeps setting itself to readonly.
Thanks

The readonly flag can be cleared by anyone with write access. If that is all then you will just need to set file attributes. However if the files ACL is blocking you (and it is easy to create an ACL that does not allow administrators) your options are more limited.
Start by finding out why the file keeps being set to read only, because if something else is updating the file you will have to coordinate with that other process otherwise all sorts of problems are likely to occur.
Best tool to see what is happening to a file is Process Monitor from SysInternals.

Related

How to write to a text file in a sub directory of program C#?

I have been writing a windows forms app for a little bit in c#. I need to write some data to a file that is in a subdirectory of the application's directory. When I create a streamwriter I am getting an exception stating that it cannot create a streamwriter because the file is already open in another process.
I have:
StreamWriter writer = new StreamWriter(Application.StartupPath + "#\database\savedStaff.txt");
And the Exception I have is this:
"The process cannot access the file.... because it is being used by another process."
I don't have anything other than visual studio that is accessing the directory. I even closed out of source tree I have for version control to make sure that wasn't the issue. Any tips on solving this would be greatly appreciated.
The error may be misleading. It may be a sharing issue, but it may also be a permissions issue. By default, the Program Files directories, and all subdirectories, require escalation to admin privileges in order to write to them. Just being logged in using an admin account typically isn't enough; you have to explicitly grant the program permission to run as an administrator. This is an anti-malware thing; theoretically, your executables cannot be modified unless you allow it through UAC. I have seen many programs, including my own, report that the file is open by another process, when the real reason Windows refused access was permissions-based.
To get around this, you can:
Have your program ask for escalation when it runs, so it can do this when necessary. This can be specified in the application manifest.
Use an installer custom routine to set more relaxed permissions on your subdirectory. I've done this myself for directories containing config files.
Change the directory being used; common alternatives include the user's AppData/Local folder under an application-specific subfolder, or a subdirectory of "My Documents" (if the file represents a unit of work produced by the program).

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.

How to Access AppData in IE Protected Mode (from a Managed BHO)

I am writing an IE Extension (BHO) in C#. When run in protected mode (IE's new UAC-compliant mode which forces all extensions to run at low-integrity), it fails because it cannot access user.config in the appdata folder.
Is there some way to mark files are readable by lower-integrity processes?
Failing that, is there some way to force the BHO to run at medium-level integrity?
Failing that, is there some way to create a low-integrity symlink in the low-integrity folders which points to a medium-integrity file in AppData?
Failing that, is there some way to force the application to use a user.config file in the LocalLow folder? How do I get the path for this folder in .net (it's not listed under Environment.SpecialFolder)? Will I be able to fall back with users running XP or who turn protected mode off, without losing all their user.config data?
There's one approach that is not especially elegant but you can start another (broker)process with medium level integrity which can do the 'dirty work' and use IPC to communicate with it. To make your life easier I would suggest you to use sockets for communication because they don't require security check which can be tricky when you have communication between processes with different integrity levels.
In order to skip UAC warning when you spawn new process you can modify BHO registration script and add few registry values that will inform IE to silently elevate new process to medium level.
You can find more information here: http://msdn.microsoft.com/en-us/library/bb250462(VS.85).aspx#wpm_elebp
I would start with the Protected Mode Internet Explorer Reference.
I suggest you to write your own SettingsProvider that saves files in System.IO.IsolatedStorage.
You get a one-shot privileged access during RegisterBHO. After that you are in protected mode.
If you need to change long term storage during the runtime of the BHO, I have found that the registry is the best place. Your changes will be only visible to you, but they will persist.

Best place to store configuration files and log files on Windows for my program?

I need to store log files and configuration files for my application. Where is the best place to store them?
Right now, I'm just using the current directory, which ends up putting them in the Program Files directory where my program lives.
The log files will probably be accessed by the user somewhat regularly, so %APPDATA% seems a little hard to get to.
Is a directory under %USERPROFILE%\My Documents the best? It needs to work for all versions of Windows, from 2000 forward.
If you're not using ConfigurationManager to manage your application and user settings, you should be. The configuration toolkit in the .NET Framework is remarkably well thought out, and the Visual Studio tools that interoperate with it are too.
The default behavior of ConfigurationManager puts both invariant (application) and modifiable (user) settings in the right places: the application settings go in the application folder, and the user settings go in System.Environment.SpecialFolder.LocalApplicationData. It works properly under all versions of Windows that support .NET.
As for log files, System.Environment.SpecialFolder.LocalApplicationData is generally the place that you want to put them, because it's guaranteed to be user-writeable.
There are certainly cases where you wouldn't - for instance, if you want to write files to a network share so that you easily can access them remotely. There's a pretty wide range of ways to implement that, but most of them start with creating an application setting that contains the path to the shared folder. All of them involve administration.
I have a couple of complaints about ConfigurationManager and the VS tools: there needs to be better high-level documentation than there is, and better documentation of the VS-generated Settings class. The mechanism by which the app.config file turns into the application configuration file in the target build directory is opaque (and the source of one of the most frequently asked questions of all: "what happened to my connection string?"). And if there's a way of creating settings that don't have default values, I haven't found it.
Note: You can get the path to the LocalApplicationData folder in .NET by using the following function:
string strPath=System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);
For application settings - use System.Environment.SpecialFolder.ApplicationData - this is where a roaming profile data is stored, so it allows your user to log and work from different machines in the domain.
For log files - System.Environment.SpecialFolder.LocalApplicationData
The accepted answer notes that for log files the following is a good spot.
System.Environment.SpecialFolder.LocalApplicationData This equates to a path of C:\Users\[User]\AppData\Roaming which you can see is user specific. Like the accepted answer mentions this is a guaranteed user-writeable location and can be useful for certain situations
However in a web application environment you may be running your application under a network account and you or a coworker may need to try and track down where exactly those logs are going per application. I personally like to use the non user specific location enumeration of
System.Environment.SpecialFolder.CommonApplicationData which equates to C:\ProgramData. Yes, you will need to specify access rights for any folders you create, but it's usually a one time deal and then all of your application logs can live in one happy location.
Additionally, while looking around the Internet, there is a project out there to programatically set write access to folders you create within CommonApplicationData, Allow write/modify access to CommonApplicationData.
To be honest %appdata% is still the best place to place your config files and log files, as it serves the purpose of a placeholder to store your application data. It should not be that hard to access, just write %appdata% in explorer and you will be directed straight to your %appdata% directory.
Do not store config files in the application folder, Microsoft has stated this is NOT the ideal location. Windows has been moving towards blocking writing to C:\Program Files\ and you'll find in Vista any application that tries to write here, will fire up a UAC warning.
Windows 7 will allow users to customize what UAC popups they use (expect some power users to block most of them) and your app will fail/freeze if the user never approves this write attempt.
If you use the proper userprofile and appdata variables, then Win 2000, XP, Vista, and Win7 will map the data to the proper write friendly folder, with no UAC popups.
You can use SHGetSpecialFolderPath:
int MAX_PATH = 255;
CString m_strMyPath;
SHGetSpecialFolderPath(NULL, m_strMyPath.GetBuffer(MAX_PATH), CSIDL_COMMON_APPDATA, TRUE);
This will specify the 'special folder path' which you can safely write logs to for windows:
For XP: C:\Documents and Settings\All Users\Application Data
For Vista: C:\ProgramData
Check the MSDN page here: http://msdn.microsoft.com/en-us/library/bb762204(VS.85).aspx
The best answer depends on the nature of the logs and configurations. If they are program-wide, and don't need to survive uninstallation of the application, then I think they're fine where they are. If the logs and configurations are user specific, or need to survive uninstallation, then they belong somewhere under %USERPROFILE% - %APPDATA% being the 'proper' base directory for this type of thing.
I use the Isolation Storage for configuration. You can also use the Temp folder to store temporary information like log.

Categories

Resources