1 //------------------------------------------------------------------------------
3 // System.Environment.cs
5 // Copyright (C) 2001 Moonlight Enterprises, All Rights Reserved
7 // Author: Jim Richardson, develop@wtfo-guru.com
8 // Dan Lewis (dihlewis@yahoo.co.uk)
9 // Created: Saturday, August 11, 2001
11 //------------------------------------------------------------------------------
13 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36 using System.Collections;
37 using System.Runtime.CompilerServices;
38 using System.Security;
39 using System.Security.Permissions;
41 using System.Runtime.InteropServices;
49 public static class Environment {
51 public sealed class Environment {
53 private Environment ()
58 * This is the version number of the corlib-runtime interface. When
59 * making changes to this interface (by changing the layout
60 * of classes the runtime knows about, changing icall signature or
61 * semantics etc), increment this variable. Also increment the
62 * pair of this variable in the runtime in metadata/appdomain.c.
63 * Changes which are already detected at runtime, like the addition
64 * of icalls, do not require an increment.
66 private const int mono_corlib_version = 77;
71 public enum SpecialFolder
72 { // TODO: Determine if these windoze style folder identifiers
73 // have unix/linux counterparts
89 DesktopDirectory = 0x10,
91 ApplicationData = 0x1a,
92 LocalApplicationData = 0x1c,
96 CommonApplicationData = 0x23,
100 CommonProgramFiles = 0x2b,
104 /// Gets the command line for this process
106 public static string CommandLine {
107 // note: security demand inherited from calling GetCommandLineArgs
109 // FIXME: we may need to quote, but any sane person
110 // should use GetCommandLineArgs () instead.
111 return String.Join (" ", GetCommandLineArgs ());
116 /// Gets or sets the current directory. Actually this is supposed to get
117 /// and/or set the process start directory acording to the documentation
118 /// but actually test revealed at beta2 it is just Getting/Setting the CurrentDirectory
120 public static string CurrentDirectory
123 return Directory.GetCurrentDirectory ();
126 Directory.SetCurrentDirectory (value);
131 /// Gets or sets the exit code of this process
133 public extern static int ExitCode
135 [MethodImplAttribute (MethodImplOptions.InternalCall)]
137 [MethodImplAttribute (MethodImplOptions.InternalCall)]
144 public extern bool HasShutdownStarted
146 [MethodImplAttribute (MethodImplOptions.InternalCall)]
152 /// Gets the name of the local computer
154 public extern static string MachineName {
155 [MethodImplAttribute (MethodImplOptions.InternalCall)]
156 [EnvironmentPermission (SecurityAction.Demand, Read="COMPUTERNAME")]
157 [SecurityPermission (SecurityAction.Demand, UnmanagedCode=true)]
162 /// Gets the standard new line value
164 public extern static string NewLine {
165 [MethodImplAttribute (MethodImplOptions.InternalCall)]
170 // Support methods and fields for OSVersion property
172 static OperatingSystem os;
174 internal static extern PlatformID Platform {
175 [MethodImplAttribute (MethodImplOptions.InternalCall)]
179 [MethodImplAttribute (MethodImplOptions.InternalCall)]
180 internal static extern string GetOSVersionString ();
183 /// Gets the current OS version information
185 public static OperatingSystem OSVersion {
188 Version v = Version.CreateFromString (GetOSVersionString ());
189 PlatformID p = Platform;
190 os = new OperatingSystem (p, v);
199 public static string StackTrace {
200 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
202 System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace (0, true);
203 return trace.ToString ();
208 /// Get a fully qualified path to the system directory
210 public static string SystemDirectory {
212 return GetFolderPath (SpecialFolder.System);
217 /// Get the number of milliseconds that have elapsed since the system was booted
219 public extern static int TickCount {
220 [MethodImplAttribute (MethodImplOptions.InternalCall)]
225 /// Get UserDomainName
227 public static string UserDomainName {
228 // FIXME: this variable doesn't exist (at least not on WinXP) - reported to MS as FDBK20562
229 [EnvironmentPermission (SecurityAction.Demand, Read="USERDOMAINNAME")]
236 /// Gets a flag indicating whether the process is in interactive mode
238 [MonoTODO ("Currently always returns false, regardless of interactive state")]
239 public static bool UserInteractive {
246 /// Get the user name of current process is running under
248 public extern static string UserName {
249 [MethodImplAttribute (MethodImplOptions.InternalCall)]
250 [EnvironmentPermission (SecurityAction.Demand, Read="USERNAME;USER")]
255 /// Get the version of the common language runtime
257 public static Version Version {
259 return new Version (Consts.FxFileVersion);
264 /// Get the amount of physical memory mapped to process
266 [MonoTODO ("Currently always returns zero")]
267 public static long WorkingSet {
268 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
272 [MethodImplAttribute (MethodImplOptions.InternalCall)]
273 [SecurityPermission (SecurityAction.Demand, UnmanagedCode=true)]
274 public extern static void Exit (int exitCode);
277 /// Substitute environment variables in the argument "name"
279 public static string ExpandEnvironmentVariables (string name)
282 throw new ArgumentNullException ("name");
284 int off1 = name.IndexOf ('%');
288 int len = name.Length;
290 if (off1 == len - 1 || (off2 = name.IndexOf ('%', off1 + 1)) == -1)
293 StringBuilder result = new StringBuilder ();
294 result.Append (name, 0, off1);
295 Hashtable tbl = null;
297 string var = name.Substring (off1 + 1, off2 - off1 - 1);
298 string value = GetEnvironmentVariable (var);
299 if (value == null && Environment.IsRunningOnWindows) {
300 // On windows, env. vars. are case insensitive
302 tbl = GetEnvironmentVariablesNoCase ();
304 value = tbl [var] as string;
307 // If value not found, add %FOO to stream,
308 // and use the closing % for the next iteration.
309 // If value found, expand it in place of %FOO%
315 result.Append (value);
318 off1 = name.IndexOf ('%', off2 + 1);
319 // If no % found for off1, don't look for one for off2
320 off2 = (off1 == -1 || off2 > len-1)? -1 :name.IndexOf ('%', off1 + 1);
321 // textLen is the length of text between the closing % of current iteration
322 // and the starting % of the next iteration if any. This text is added to output
324 // If no new % found, use all the remaining text
325 if (off1 == -1 || off2 == -1)
326 textLen = len - oldOff2 - 1;
327 // If value found in current iteration, use text after current closing % and next %
328 else if(value != null)
329 textLen = off1 - oldOff2 - 1;
330 // If value not found in current iteration, but a % was found for next iteration,
331 // use text from current closing % to the next %.
333 textLen = off1 - oldOff2;
334 if(off1 >= oldOff2 || off1 == -1)
335 result.Append (name, oldOff2+1, textLen);
336 } while (off2 > -1 && off2 < len);
338 return result.ToString ();
343 /// Return an array of the command line arguments of the current process
345 [MethodImplAttribute (MethodImplOptions.InternalCall)]
346 [EnvironmentPermissionAttribute (SecurityAction.Demand, Read = "PATH")]
347 public extern static string[] GetCommandLineArgs ();
349 [MethodImplAttribute (MethodImplOptions.InternalCall)]
350 internal extern static string internalGetEnvironmentVariable (string variable);
353 /// Return a string containing the value of the environment
354 /// variable identifed by parameter "variable"
356 public static string GetEnvironmentVariable (string variable)
358 if (SecurityManager.SecurityEnabled) {
359 new EnvironmentPermission (EnvironmentPermissionAccess.Read, variable).Demand ();
361 return internalGetEnvironmentVariable (variable);
364 static Hashtable GetEnvironmentVariablesNoCase ()
366 Hashtable vars = new Hashtable (CaseInsensitiveHashCodeProvider.Default,
367 CaseInsensitiveComparer.Default);
369 foreach (string name in GetEnvironmentVariableNames ()) {
370 vars [name] = internalGetEnvironmentVariable (name);
377 /// Return a set of all environment variables and their values
380 public static IDictionary GetEnvironmentVariables ()
382 StringBuilder sb = null;
383 if (SecurityManager.SecurityEnabled) {
384 // we must have access to each variable to get the lot
385 sb = new StringBuilder ();
386 // but (performance-wise) we do not want a stack-walk
387 // for each of them so we concatenate them
390 Hashtable vars = new Hashtable ();
391 foreach (string name in GetEnvironmentVariableNames ()) {
392 vars [name] = internalGetEnvironmentVariable (name);
400 new EnvironmentPermission (EnvironmentPermissionAccess.Read, sb.ToString ()).Demand ();
405 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
406 public static IDictionary GetEnvironmentVariables ()
408 Hashtable vars = new Hashtable ();
409 foreach (string name in GetEnvironmentVariableNames ()) {
410 vars [name] = internalGetEnvironmentVariable (name);
416 [MethodImplAttribute (MethodImplOptions.InternalCall)]
417 private extern static string GetWindowsFolderPath (int folder);
420 /// Returns the fully qualified path of the
421 /// folder specified by the "folder" parameter
423 public static string GetFolderPath (SpecialFolder folder)
427 if (Environment.IsRunningOnWindows) {
428 dir = GetWindowsFolderPath ((int) folder);
430 dir = InternalGetFolderPath (folder);
433 if ((dir != null) && (dir.Length > 0) && SecurityManager.SecurityEnabled) {
434 new FileIOPermission (FileIOPermissionAccess.PathDiscovery, dir).Demand ();
439 private static string ReadXdgUserDir (string config_dir, string home_dir,
440 string key, string fallback)
442 string env_path = internalGetEnvironmentVariable (key);
443 if (env_path != null && env_path != String.Empty) {
447 string user_dirs_path = Path.Combine (config_dir, "user-dirs.dirs");
449 if (!File.Exists (user_dirs_path)) {
450 return Path.Combine (home_dir, fallback);
454 using(StreamReader reader = new StreamReader (user_dirs_path)) {
456 while ((line = reader.ReadLine ()) != null) {
458 int delim_index = line.IndexOf ('=');
459 if(delim_index > 8 && line.Substring (0, delim_index) == key) {
460 string path = line.Substring (delim_index + 1).Trim ('"');
461 bool relative = false;
463 if (path.StartsWith ("$HOME/")) {
465 path = path.Substring (6);
466 } else if (!path.StartsWith ("/")) {
470 return relative ? Path.Combine (home_dir, path) : path;
474 } catch (FileNotFoundException) {
477 return Path.Combine (home_dir, fallback);
481 // the security runtime (and maybe other parts of corlib) needs the
482 // information to initialize themselves before permissions can be checked
483 internal static string InternalGetFolderPath (SpecialFolder folder)
485 string home = internalGetHome ();
487 // http://freedesktop.org/Standards/basedir-spec/basedir-spec-0.6.html
489 // note: skip security check for environment variables
490 string data = internalGetEnvironmentVariable ("XDG_DATA_HOME");
491 if ((data == null) || (data == String.Empty)) {
492 data = Path.Combine (home, ".local");
493 data = Path.Combine (data, "share");
496 // note: skip security check for environment variables
497 string config = internalGetEnvironmentVariable ("XDG_CONFIG_HOME");
498 if ((config == null) || (config == String.Empty)) {
499 config = Path.Combine (home, ".config");
504 // MyComputer is a virtual directory
505 case SpecialFolder.MyComputer:
509 case SpecialFolder.Personal:
511 // use FDO's CONFIG_HOME. This data will be synced across a network like the windows counterpart.
512 case SpecialFolder.ApplicationData:
514 //use FDO's DATA_HOME. This is *NOT* synced
515 case SpecialFolder.LocalApplicationData:
518 case SpecialFolder.Desktop:
520 case SpecialFolder.DesktopDirectory:
521 return ReadXdgUserDir (config, home, "XDG_DESKTOP_DIR", "Desktop");
523 case SpecialFolder.MyMusic:
524 return ReadXdgUserDir (config, home, "XDG_MUSIC_DIR", "Music");
526 case SpecialFolder.MyPictures:
527 return ReadXdgUserDir (config, home, "XDG_PICTURES_DIR", "Pictures");
529 // these simply dont exist on Linux
530 // The spec says if a folder doesnt exist, we
532 case SpecialFolder.Favorites:
533 case SpecialFolder.Programs:
534 case SpecialFolder.SendTo:
535 case SpecialFolder.StartMenu:
536 case SpecialFolder.Startup:
537 case SpecialFolder.Templates:
538 case SpecialFolder.Cookies:
539 case SpecialFolder.History:
540 case SpecialFolder.InternetCache:
541 case SpecialFolder.Recent:
542 case SpecialFolder.CommonProgramFiles:
543 case SpecialFolder.ProgramFiles:
544 case SpecialFolder.System:
546 // This is where data common to all users goes
547 case SpecialFolder.CommonApplicationData:
550 throw new ArgumentException ("Invalid SpecialFolder");
554 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
555 public static string[] GetLogicalDrives ()
557 return GetLogicalDrivesInternal ();
560 #if NET_2_0 && !NET_2_1
561 [MethodImplAttribute (MethodImplOptions.InternalCall)]
562 private static extern void internalBroadcastSettingChange ();
564 public static string GetEnvironmentVariable (string variable, EnvironmentVariableTarget target)
567 case EnvironmentVariableTarget.Process:
568 return GetEnvironmentVariable (variable);
569 case EnvironmentVariableTarget.Machine:
570 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
571 if (!IsRunningOnWindows)
573 using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment")) {
574 object regvalue = env.GetValue (variable);
575 return (regvalue == null) ? null : regvalue.ToString ();
577 case EnvironmentVariableTarget.User:
578 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
579 if (!IsRunningOnWindows)
581 using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.CurrentUser.OpenSubKey ("Environment", false)) {
582 object regvalue = env.GetValue (variable);
583 return (regvalue == null) ? null : regvalue.ToString ();
586 throw new ArgumentException ("target");
590 public static IDictionary GetEnvironmentVariables (EnvironmentVariableTarget target)
592 IDictionary variables = (IDictionary)new Hashtable ();
594 case EnvironmentVariableTarget.Process:
595 variables = GetEnvironmentVariables ();
597 case EnvironmentVariableTarget.Machine:
598 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
599 if (IsRunningOnWindows) {
600 using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment")) {
601 string[] value_names = env.GetValueNames ();
602 foreach (string value_name in value_names)
603 variables.Add (value_name, env.GetValue (value_name));
607 case EnvironmentVariableTarget.User:
608 new EnvironmentPermission (PermissionState.Unrestricted).Demand ();
609 if (IsRunningOnWindows) {
610 using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.CurrentUser.OpenSubKey ("Environment")) {
611 string[] value_names = env.GetValueNames ();
612 foreach (string value_name in value_names)
613 variables.Add (value_name, env.GetValue (value_name));
618 throw new ArgumentException ("target");
623 [EnvironmentPermission (SecurityAction.Demand, Unrestricted=true)]
624 public static void SetEnvironmentVariable (string variable, string value)
626 SetEnvironmentVariable (variable, value, EnvironmentVariableTarget.Process);
629 [EnvironmentPermission (SecurityAction.Demand, Unrestricted = true)]
630 public static void SetEnvironmentVariable (string variable, string value, EnvironmentVariableTarget target)
632 if (variable == null)
633 throw new ArgumentNullException ("variable");
634 if (variable == String.Empty)
635 throw new ArgumentException ("String cannot be of zero length.", "variable");
636 if (variable.IndexOf ('=') != -1)
637 throw new ArgumentException ("Environment variable name cannot contain an equal character.", "variable");
638 if (variable[0] == '\0')
639 throw new ArgumentException ("The first char in the string is the null character.", "variable");
642 case EnvironmentVariableTarget.Process:
643 InternalSetEnvironmentVariable (variable, value);
645 case EnvironmentVariableTarget.Machine:
646 if (!IsRunningOnWindows)
648 using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.LocalMachine.OpenSubKey (@"SYSTEM\CurrentControlSet\Control\Session Manager\Environment", true)) {
649 if (String.IsNullOrEmpty (value))
650 env.DeleteValue (variable, false);
652 env.SetValue (variable, value);
653 internalBroadcastSettingChange ();
656 case EnvironmentVariableTarget.User:
657 if (!IsRunningOnWindows)
659 using (Microsoft.Win32.RegistryKey env = Microsoft.Win32.Registry.CurrentUser.OpenSubKey ("Environment", true)) {
660 if (String.IsNullOrEmpty (value))
661 env.DeleteValue (variable, false);
663 env.SetValue (variable, value);
664 internalBroadcastSettingChange ();
668 throw new ArgumentException ("target");
672 [MethodImplAttribute (MethodImplOptions.InternalCall)]
673 internal static extern void InternalSetEnvironmentVariable (string variable, string value);
675 [MonoTODO ("Not implemented")]
676 [SecurityPermission (SecurityAction.LinkDemand, UnmanagedCode=true)]
677 public static void FailFast (string message)
679 throw new NotImplementedException ();
683 public static extern int ProcessorCount {
684 [EnvironmentPermission (SecurityAction.Demand, Read="NUMBER_OF_PROCESSORS")]
685 [MethodImplAttribute (MethodImplOptions.InternalCall)]
691 internal static bool IsRunningOnWindows {
692 get { return ((int) Platform < 4); }
696 // Used by gacutil.exe
698 #pragma warning disable 169
699 private static string GacPath {
701 if (Environment.IsRunningOnWindows) {
702 /* On windows, we don't know the path where mscorlib.dll will be installed */
703 string corlibDir = new DirectoryInfo (Path.GetDirectoryName (typeof (int).Assembly.Location)).Parent.Parent.FullName;
704 return Path.Combine (Path.Combine (corlibDir, "mono"), "gac");
707 return Path.Combine (Path.Combine (internalGetGacPath (), "mono"), "gac");
710 #pragma warning restore 169
711 [MethodImplAttribute (MethodImplOptions.InternalCall)]
712 internal extern static string internalGetGacPath ();
714 [MethodImplAttribute (MethodImplOptions.InternalCall)]
715 private extern static string [] GetLogicalDrivesInternal ();
717 [MethodImplAttribute (MethodImplOptions.InternalCall)]
718 private extern static string [] GetEnvironmentVariableNames ();
720 [MethodImplAttribute (MethodImplOptions.InternalCall)]
721 internal extern static string GetMachineConfigPath ();
723 [MethodImplAttribute (MethodImplOptions.InternalCall)]
724 internal extern static string internalGetHome ();