Environment.GetFolderPath(Environment.SpecialFolde

2019-04-10 09:05发布

问题:

i have an asp.net mvc3 application. Now i want to save userdata in

C:\Users{AppPoolUserAccount}\AppData\Roaming\MyProgramm...

On first call of Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) i only get "" (String.Empty). On second call Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) returns correct path...

Note: The routine is in a Login-Context. I want to save username and sessionID in a xml-file to prevent that two users are logged in simultaneously via one user-account.

Why?

回答1:

Environment.GetFolderPath returns empty strings for most of the SpecialFolder enum values because the user profile for the user you are using to run the app pool is not loaded.

You need to configure the app pool to load the user profile either by going into IIS Manager > Application Pools > YourAppPool > Advanced Settings > Load User Profile, and setting the value to "true" or by opening up a command prompt and running

appcmd set apppool "MyAppPool" -processModel.loadUserProfile:true

(usually you'll run this in C:\Windows\SysWOW64\inetsrv).

Here are a couple of links with more data:

  • loadUserProfile and IIS7 (This one says that loading the profile is the default, which it isn't, but it is correct otherwise. Maybe they changed the default between 7 and 7.5?)
  • Process Model Settings for an Application Pool


回答2:

If you want to share data (for example currently logged users) try use this code:

In global.asax, when application starts:

 var users = new List<Guid>();
 Application["loggedUsers"] = users;

Then if user is logging on, type this:

var users = (List<Guid>)Application["loggedUsers"];
users.Add(currentlyLoggingOnUserId);
Application["loggedUsers"] = users;


回答3:

Environment.GetFolderPathreturns an empty string by design if the folder does not exist. From MSDN:

Environment.GetFolderPath Method (Environment.SpecialFolder)

Return Value Type: System.String

The path to the specified system special folder, if that folder physically exists on your computer; otherwise, an empty string ("").

A folder will not physically exist if the operating system did not create it, the existing folder was deleted, or the folder is a virtual directory, such as My Computer, which does not correspond to a physical path.