简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM