C # read "My Documents" and other special system paths and environment variables

Source: Internet
Author: User
Tags mssqlserver

Returns the "My Documents" path string

Environment.getfolderpath (Environment.SpecialFolder.Personal)

This tip uses the GetFolderPath method to obtain a path to the system special folder identified by the specified enumeration. The syntax format is as follows:

public static string GetFolderPath (SpecialFolder folder)

The parameter folder identifies the enumeration constants of the system's special folders.

If a special folder for the specified system exists on the user's computer, the path to the folder is returned, otherwise an empty string (""). If the system does not create a folder, the existing folder is deleted, or the folder is a virtual directory that does not have a physical path (for example, "My Computer"), the folder does not actually exist.

The main code is as follows:

MessageBox.Show ("My Document System path:" + Environment.getfolderpath (Environment.SpecialFolder.Personal), "My Documents", Messageboxbuttons.ok,messageboxicon.information);


Reference one: How C # Gets the directory for a user's My Documents
Console.WriteLine (System.Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments));

System.Environment.GetFolderPath method
Gets the path to the System special folder identified by the specified enumeration.

public static string GetFolderPath (
Environment.SpecialFolder folder
)
Environment.SpecialFolder Enumeration Description:
Member name Description
The ApplicationData directory, which serves as the common repository for application-specific data for the current roaming user.
The Commonapplicationdata directory, which serves as a common repository for application-specific data that is used by all users.
The Localapplicationdata directory, which serves as a common repository for application-specific data that is currently used by non-roaming users.
Cookies are used as directories for public repositories of Internet cookies.
Desktop logical desktops, not physical file system locations.
Favorites a directory that serves as a common repository for user favorite items.
History the directory that is used as the public repository for Internet Chronicle items.
Internetcache is used as a directory for public repositories of temporary Internet files.
Programs contains a directory of user program groups.
MyComputer the "My Computer" folder.
MyMusic the "My Music" folder.
MyPictures the "My Pictures" folder.
Recent The directory that contains the documents that the user has recently used.
SendTo the directory containing the Send menu item.
StartMenu the directory containing the Start menu item.
Startup directory that corresponds to the user's startup program group.
System "System" directory.
Templates a directory that is used as a common repository for document templates.
The desktopdirectory is used to physically store the directory of File objects on the desktop.
Personal the directory that is used as a common repository for documents.
MyDocuments the "My Computer" folder.
ProgramFiles the "Program Files" directory.
CommonProgramFiles the directory for components that are shared among applications.


Reference two: C # Open the desktop and other special system paths

Different operating systems, the path of the desktop is not the same, and with the user installation location is different.
C # can be read from the Windows registry to get the location of a user's special folder (desktop, Favorites, and so on).
The code is as follows:

Using Microsoft.Win32;
Namespace Jpgcompact
{
public partial class Mainform:form
{
private void Test ()
{
RegistryKey folders;
Folders = Openregistrypath (Registry.currentuser, @ "\software\microsoft\windows\currentversion\explorer\shell Folders ");
Windows user Desktop Path
String DesktopPath = Folders. GetValue ("Desktop"). ToString ();
Windows user Font directory path
String fontspath = Folders. GetValue ("Fonts"). ToString ();
Windows User Network Neighbor Path
String nethoodpath = Folders. GetValue ("NetHood"). ToString ();
Windows user My Documents path
String personalpath = Folders. GetValue ("Personal"). ToString ();
Windows user Start Menu program path
String programspath = Folders. GetValue ("Programs"). ToString ();
directory path for Windows users to store shortcuts to documents that users have recently accessed
String recentpath = Folders. GetValue ("recent"). ToString ();
Windows users send to directory path
String sendtopath = Folders. GetValue ("Sendto"). ToString ();
Windows user Start Menu directory path
String startmenupath = Folders. GetValue ("StartMenu"). ToString ();
Windows user Start menu startup item directory path
String startuppath = Folders. GetValue ("Startup"). ToString ();
Windows User Favorites directory path
String favoritespath = Folders. GetValue ("Favorites"). ToString ();
Windows user page history directory path
String historypath = Folders. GetValue ("History"). ToString ();
Windows User Cookies directory path
String cookiespath = Folders. GetValue ("Cookies"). ToString ();
Windows user Cache directory path
String CachePath = Folders. GetValue ("Cache"). ToString ();
Windows user Application Data directory path
String appdatapath = Folders. GetValue ("Appdata"). ToString ();
Windows user Print directory path
String printhoodpath = Folders. GetValue ("PrintHood"). ToString ();
}

        Private RegistryKey Openregistrypath (RegistryKey root, string s)
        {
             s = s.remove (0, 1) + @ "\";
            while (s.indexof (@ "\")! =-1)
             {
                 root = root. OpenSubKey (s.substring (0, S.indexof (@ "\")));
                s = s.remove (0, s). IndexOf (@ "\") + 1);
           }
            return root;
       }
   }

C # reads system environment variables, my document paths, desktop paths, and so on

1
Direct system.environment.getenvironmentvariable["variable name"];
such as getting a computer name, program folder, etc.
[SourceCode language= ' C # ']
TextBox1.Text = System.Environment.GetEnvironmentVariable ("COMPUTERNAME") + "RN";
TextBox1.Text = System.Environment.GetEnvironmentVariable ("programfiles") + "RN";
[/sourcecode]

As for "desktop" "My Documents" can be so

[Code language= ' C # ']
TextBox1.Text + = Environment.getfolderpath (Environment.SpecialFolder.Personal) + "RN";//My Documents
TextBox1.Text + = Environment.getfolderpath (Environment.SpecialFolder.Desktop) + "RN";//Desktop
[/code]
is to use Environment.getfolderpath (Environment.SpecialFolder. Special folders)
such as cookies, music, video, send to, and so on can get the path

2

C # Read the environment variables of the system

Using System;
Using System.Collections;

Class Foreachapp
{
    public static void Main ()
    {
        //Take out all the values in the environment variables and put them in the variable environment
        IDictionary environment = Environment.getenvironmentvariables ();
       
       //print header
         Console.WriteLine ("Environment variable name \t=\t environment variable value");

Traverse all key values in environment
foreach (String Environmentkey in environment. Keys)
{
Print out the names and values of all environment variables
Console.WriteLine ("{0}\t=\t{1}", Environmentkey, Environment[environmentkey]. ToString ());
}
}
}

3

C # Read set PATH environment variable and restart computer

Using System;
Using System.Collections.Generic;
Using System.ComponentModel;
Using System.Data;
Using System.Drawing;
Using System.Text;
Using System.Windows.Forms;
Using the microsoft.win32;//registry operation to reference the space
The using system.runtime.interopservices;//invokes the reference required by the API function to load the unmanaged class User32.dll


Namespace modifying environment variables with a program
{
public partial class Form1:form
{
Public Form1 ()
{
InitializeComponent ();
}

private void Form1_Load (object sender, EventArgs e)
{

}
<summary>
Read the Registration Form
Path: [HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Control\Session Manager\Environment]
</summary>
<param name= "Sender" ></param>
<param name= "E" ></param>
private void Tbnread_click (object sender, EventArgs e)
{
RegistryKey reglocalmachine = registry.localmachine;
RegistryKey Regsystem = Reglocalmachine.opensubkey ("System", true);//Open SYSTEM under HKEY_LOCAL_MACHINE
RegistryKey regControlSet001 = Regsystem.opensubkey ("ControlSet001", true);//Open ControlSet001
RegistryKey Regcontrol = Regcontrolset001.opensubkey ("control", true);//Open Control
RegistryKey Regmanager = Regcontrol.opensubkey ("Session Manager", true);//Open Control

RegistryKey regenvironment = Regmanager.opensubkey ("Environment", true);//opening MSSQLServer MSSQLSERVER
This.richTextBox1.Text = Regenvironment.getvalue ("path"). ToString ();//Read the value of path
}

private void btnClose_Click (object sender, EventArgs e)
{
Close ();
}

       //<summary>
       /
       //</summary>
        //<param name= "sender" ></PARAM>
       //<param Name= "E" ></PARAM>
        [DllImport ("user32.dll", SetLastError = True, CharSet = CharSet.Auto)]//sendmessagetimeout is defined in User32.dll
        public static extern IntPtr SendMessageTimeout (
     IntPtr windowhandle,
      uint MSG,
     IntPtr wParam,
     IntPtr LParam,
     sendmessagetimeoutflags flags,
     UINT timeout,
      out IntPtr result
    );

[Flags]
public enum Sendmessagetimeoutflags:uint
{
Smto_normal = 0x0000,
Smto_block = 0x0001,
Smto_abortifhung = 0x0002,
Smto_notimeoutifnothung = 0x0008
}

private void Btnwrite_click (object sender, EventArgs e)
{

            RegistryKey reglocalmachine = Registry.localmachine;
            RegistryKey Regsystem = Reglocalmachine.opensubkey ("System", true);//Open HKEY_LOCAL_MACHINE under System
             RegistryKey regControlSet001 = Regsystem.opensubkey ("ControlSet001", true);// Open ControlSet001
            RegistryKey Regcontrol = Regcontrolset001.opensubkey ("Control", true);//Open Control
             RegistryKey Regmanager = Regcontrol.opensubkey ("Session Manager", true);//Open Control

            RegistryKey regenvironment = Regmanager.opensubkey ("Environment", true);//Open MSSQLServer under MSSQLSERVER
             regenvironment.setvalue ("path", this.richTextBox1.Text);//Read the value of path


MessageBox.Show ("modified successfully");
Use the Send system message below to not restart the computer.
const int HWND_BROADCAST=0XFFFF;
DWORD Dwmsgresult = 0L;
const UINT WM_SETTINGCHANGE = 0;
Const long Smto_abortifhung = 0x2;
System.UInt32 dwmsgresult1=0;
Long S;
SendMessageTimeout (Hwnd_broadcast, Wm_settingchange, 0, (String) "Environment", Smto_abortifhung, and (long) s);

}
<summary>
Restart your computer
</summary>
<param name= "x" ></param>
<param name= "Y" ></param>
<returns></returns>
[DllImport ("User32.dll")]
The main API is this, note: must be declared as static extern
private static extern int ExitWindowsEx (int x, int y);
private void Button1_Click (object sender, EventArgs e)
{
ExitWindowsEx (2,0);
}
}
}

C # read "My Documents" and other special system paths and environment variables

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.