System.UnauthorizedAccess Exception C#

Sandeep Bansal picture Sandeep Bansal · Jan 24, 2010 · Viewed 7.1k times · Source

I currently have a compiled C# program but whenever I run it I get the Windows encountered a problem error.

This is from a System.UnauthorizedAccess error, how can I give access and remove this error without any need from the user side, since this program is being deployed to a lot of people and I don't want them having to make this fix manually.

Thanks

Answer

atanamir picture atanamir · Jan 24, 2010

You can get the current user's application data folder using the environment variable APPDATA. Therefore, you can do something like:

string appdata = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
string configFile = Path.Combine(appdata, configFile);
StreamWriter writer = new StreamWriter(configFile);
writer.WriteLine("my config data");
writer.Close();

You can also use this approach to get the temporary folder as well. You can even generate a random file name using the BCL functions. I think it's Path.GetTempFilename().