%AllUsersProfile%(%PROGRAMDATA%) gives a repetitive file path

Christian picture Christian · Dec 4, 2012 · Viewed 10.1k times · Source

I have an application written in C#, and I am seeking to write some information to the hidden ProgramData in order to access the same connection string from both the application's front end and back end.

I am accessing the directory using path variables as follows:

private bool ProgramDataWriteFile(string contentToWrite)
        {
            try
            {

                string strProgramDataPath = "%PROGRAMDATA%";
                string directoryPath = Environment.ExpandEnvironmentVariables(strProgramDataPath) + "\\MyApp\\";
                string path = Environment.ExpandEnvironmentVariables(strProgramDataPath)+"\\MyApp\\ConnectionInfo.txt";

                if (Directory.Exists(directoryPath))
                {
                    System.IO.StreamWriter file = new System.IO.StreamWriter(path);
                    file.Write(contentToWrite);
                    file.Close();
                }
                else
                {
                    Directory.CreateDirectory(directoryPath);
                    System.IO.StreamWriter file = new System.IO.StreamWriter(path);
                    file.Write(contentToWrite);
                    file.Close();
                }

                return true;
            }
            catch (Exception e)
            {
            }
            return false;
        }

This seems to work correctly. However, my question is, when I used this path variable: %AllUsersProfile%(%PROGRAMDATA%) instead, it expanded into an illegal(and redundant) file path : C:\ProgramData(C:\ProgramData)\ However, I thought that the latter path variable was the correct full name. Was I just using it incorrectly? I need to ensure that this connection info will be accessible to all users, will just using %PROGRAMDATA% allow that? I am using Windows 7 in case that is relevant.

Answer

spender picture spender · Dec 4, 2012

From here:

FOLDERID_ProgramData / System.Environment.SpecialFolder.CommonApplicationData

The user would never want to browse here in Explorer, and settings changed here should affect every user on the machine. The default location is %systemdrive%\ProgramData, which is a hidden folder, on an installation of Windows Vista. You'll want to create your directory and set the ACLs you need at install time.

So, just use %PROGRAMDATA%, or better still:

Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)