PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, October 19, 2022

[FIXED] How do i get access to C:\Program Files\ in c#

 October 19, 2022     admin, c#, subdirectory, unauthorizedaccessexcepti, windows     No comments   

Issue

I want to save my Files in a more generic way than on Desktop. So i want to create my own Subfolder in Programs Folder, which i can use to save my stuff. But i get "System.UnauthorizedAccessException" if i try to create a File using File.AppendAllText(@"C:\Program Files\MySubfolder\MyFile.txt,someString);

I even disabled the Protection of the Folders manually. My App is not yet compiled so i cant run it as administrator, can i? How does every Program use this Folder but i cant? Do i need to compile my App everytime i make a small change and want to test it?

I would really apreciate Help since im stuck with that multiple hours now


Solution

It is a very bad practice to try to write in Program Files. This folder as well as other sensitive folders are protected by the OS to prevent malicious code hide between your programs or to prevent unsavy users from messing on the installed programs.

If you want to write your private stuff on your disk you can use these folders

string folder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string myFolder = Path.Combine(folder, "MyReservedPath");
Directory.CreateDirectory(myFolder);  // if exists does nothing
string myFile = Path.Combine(myFolder, "MyPrivateData.txt");
File.WriteAllText(myFile, dataToWriteOnDisk);

The CommonApplicationData resolves to C:\programdata and this place is usually used to store information needed by your program for any user that uses it.

If you want to store some data that your program produces then it is better to use the

Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

There are many other places available, just look at the Environment.SpecialFolder enum.

This code will give you a list of everything mapped to the actual folders in your system

foreach (Environment.SpecialFolder x in Enum.GetValues(typeof(Environment.SpecialFolder)))
    Console.WriteLine($"{x} = {Environment.GetFolderPath(x)}");


Answered By - Steve
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing