Q:

Could my code cause a crash when creating a new file and directory under Windows 7?

I have had some problems earlier which caused my program to crash in all Windows OS because I did not create a new file/directory for my file. Then I have assured that I have created file/folder before initializing ect. Now my program works in Windows XP but it doesn't work in Windows 7. By saying that it works I mean that it creates a file/folder needed for my program. By not working I mean that the file/folder isn't created in windows 7.
Could this code be the cause of the crash under Windows 7? If so, how could I fix it?
    private static string dir = Environment.GetFolderPath
        (Environment.SpecialFolder.ProgramFiles) + @"\folder\";
    private static string file = dir + @"\Settings.txt";
    private string text;

    public void CheckFileStatus()
    {
        if (!Directory.Exists(dir))
        {
            DirectoryInfo directory = Directory.CreateDirectory(dir);
        }
        if (!File.Exists(file))
        {
            using (FileStream fileStream = File.Create(file))
            {
            }
        }
    }

A:

The program files directory in Windows 7 can only be written to with elevated privileges. Are you running your code as an administrator? It's also bad practice to write to the program files folder. You should be using the %appdata% folder.
Take a look here to see the various special folders. You will likely want to use either System.Environment.SpecialFolder.ApplicationData or System.Environment.SpecialFolder.CommonApplicationData. This will allow you to write data without needing elevated privileges.

A:

You cannot create folders in Program Files without being having elevated privileges (ie acting as an Administrator) on Windows Vista and Windows 7. There are generally better places to put settings files that should be writable by any user.
Environment.SpecialFolder.ApplicationData or Environment.SpecialFolder.LocalApplicationData  is generally the place for user specific application data which is most likely what you want.
The difference being that in a domain, ApplicationData will be placed in your roaming profile and be shared between computers on the domain, while LocalApplicationData is for that very machine only. 
For home users or if you don't specifically want the data to be shared between machines, probably LocalApplicationData is better. That way you know it won't cause problems on a domain if you end up writing computer specific data in it.
There is also Environment.SpecialFolder.CommonApplicationData which allows for sharing the same data between all users on the computer, but while that may seem convenient, consider that any user on the machine can then change settings of a program that is later run by you which may cause security implications.

