返回“我的文档”路径字符串

Environment.GetFolderPath(Environment.SpecialFolder.Personal)

本技巧使用GetFolderPath方法来获取指向由指定枚举标识的系统特殊文件夹的路径。语法格式如下:

public static string GetFolderPath (SpecialFolder folder)

参数folder标识系统特殊文件夹的枚举常数。

如果指定系统的特殊文件夹存在于用户的计算机上,则返回到该文件夹的路径;否则为空字符串(" ")。如果系统未创建文件夹、已删除现有文件夹或者文件夹是不对应物理路径的虚拟目录(例如“我的电脑”),则该文件夹不会实际存在。

主要代码如下:

MessageBox.Show("我的文档系统路径:" + Environment.GetFolderPath(Environment.SpecialFolder.Personal), "我的文档",MessageBoxButtons.OK,MessageBoxIcon.Information);

参考一:C# 如何获取某用户的“我的文档”的目录
Console.WriteLine(System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));

System.Environment.GetFolderPath 方法
获取指向由指定枚举标识的系统特殊文件夹的路径。

public static string GetFolderPath(
Environment.SpecialFolder folder
)
Environment.SpecialFolder 枚举说明:
成员名称 说明 
ApplicationData 目录,它用作当前漫游用户的应用程序特定数据的公共储存库。 
CommonApplicationData 目录,它用作所有用户使用的应用程序特定数据的公共储存库。 
LocalApplicationData 目录,它用作当前非漫游用户使用的应用程序特定数据的公共储存库。 
Cookies 用作 Internet Cookie 的公共储存库的目录。 
Desktop 逻辑桌面,而不是物理文件系统位置。 
Favorites 用作用户收藏夹项的公共储存库的目录。 
History 用作 Internet 历史记录项的公共储存库的目录。 
InternetCache 用作 Internet 临时文件的公共储存库的目录。 
Programs 包含用户程序组的目录。 
MyComputer “我的电脑”文件夹。  
MyMusic “My Music”文件夹。 
MyPictures “My Pictures”文件夹。 
Recent 包含用户最近使用过的文档的目录。 
SendTo 包含“发送”菜单项的目录。 
StartMenu 包含“开始”菜单项的目录。 
Startup 对应于用户的“启动”程序组的目录。 
System “System”目录。 
Templates 用作文档模板的公共储存库的目录。 
DesktopDirectory 用于物理上存储桌面上的文件对象的目录。 
Personal 用作文档的公共储存库的目录。 
MyDocuments “我的电脑”文件夹。 
ProgramFiles “Program files”目录。 
CommonProgramFiles 用于应用程序间共享的组件的目录。

参考二:C#打开桌面等特殊系统路径

不同的操作系统,桌面的路径不尽相同,而且随着用户安装位置的不同也不同。
C#可以从Windows注册表读取得到用户的特殊文件夹(桌面、收藏夹等等)的位置。
代码如下:

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用户桌面路径
            string desktopPath = folders.GetValue("Desktop").ToString();
            // Windows用户字体目录路径
            string fontsPath = folders.GetValue("Fonts").ToString();
            // Windows用户网络邻居路径
            string nethoodPath = folders.GetValue("Nethood").ToString();
            // Windows用户我的文档路径
            string personalPath = folders.GetValue("Personal").ToString();
            // Windows用户开始菜单程序路径
            string programsPath = folders.GetValue("Programs").ToString();
            // Windows用户存放用户最近访问文档快捷方式的目录路径
            string recentPath = folders.GetValue("Recent").ToString();
            // Windows用户发送到目录路径
            string sendtoPath = folders.GetValue("Sendto").ToString();
            // Windows用户开始菜单目录路径
            string startmenuPath = folders.GetValue("Startmenu").ToString();
            // Windows用户开始菜单启动项目录路径
            string startupPath = folders.GetValue("Startup").ToString();
            // Windows用户收藏夹目录路径
            string favoritesPath = folders.GetValue("Favorites").ToString();
            // Windows用户网页历史目录路径
            string historyPath = folders.GetValue("History").ToString();
            // Windows用户Cookies目录路径
            string cookiesPath = folders.GetValue("Cookies").ToString();
            // Windows用户Cache目录路径
            string cachePath = folders.GetValue("Cache").ToString();
            // Windows用户应用程式数据目录路径
            string appdataPath = folders.GetValue("Appdata").ToString();
            // Windows用户打印目录路径
            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#中读取系统的环境变量、我的文档路径、桌面路径等

1
直接System.Environment.GetEnvironmentVariable["变量名"];
比如得到计算机名、程序文件夹等
[sourcecode language='c#']
TextBox1.Text = System.Environment.GetEnvironmentVariable(“COMPUTERNAME”) +”rn”;
TextBox1.Text = System.Environment.GetEnvironmentVariable(“ProgramFiles”) +”rn”;
[/sourcecode]

至于像“桌面”“我的文档”可以这么得到

[code language='C#']
TextBox1.Text += Environment.GetFolderPath(Environment.SpecialFolder.Personal)+ "rn";//我的文档
TextBox1.Text += Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "rn";//桌面
[/code]
就是用Environment.GetFolderPath(Environment.SpecialFolder.特殊文件夹)
像cookies、音乐、视频、发送到等等都可以这样获得路径

2

C#读取系统的环境变量

using System;
using System.Collections;

class ForeachApp
{
    public static void Main()
    {
        // 把环境变量中所有的值取出来,放到变量environment中
        IDictionary environment = Environment.GetEnvironmentVariables();
       
        // 打印表头
        Console.WriteLine("环境变量名\t=\t环境变量值");

// 遍历environment中所有键值
        foreach (string environmentKey in environment.Keys)
        {
            // 打印出所有环境变量的名称和值
            Console.WriteLine("{0}\t=\t{1}", environmentKey, environment[environmentKey].ToString());
        }
    }
}

3

C#读取设置path环境变量并重启计算机

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;//注册表操作要引用的空间
using System.Runtime.InteropServices;//调用API函数需要的引用,来加载非托管类user32.dll

namespace 用程序修改环境变量
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

private void Form1_Load(object sender, EventArgs e)
        {

}
        /// <summary>
        /// 读取注册表
        /// 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);//打开HKEY_LOCAL_MACHINE下的SYSTEM
            RegistryKey regControlSet001 = regSYSTEM.OpenSubKey("ControlSet001", true);//打开ControlSet001
            RegistryKey regControl = regControlSet001.OpenSubKey("Control", true);//打开Control
            RegistryKey regManager = regControl.OpenSubKey("Session Manager", true);//打开Control

RegistryKey regEnvironment = regManager.OpenSubKey("Environment", true);//打开MSSQLServer下的MSSQLServer
            this.richTextBox1.Text = regEnvironment.GetValue("path").ToString();//读取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是在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);//打开HKEY_LOCAL_MACHINE下的SYSTEM
            RegistryKey regControlSet001 = regSYSTEM.OpenSubKey("ControlSet001", true);//打开ControlSet001
            RegistryKey regControl = regControlSet001.OpenSubKey("Control", true);//打开Control
            RegistryKey regManager = regControl.OpenSubKey("Session Manager", true);//打开Control

RegistryKey regEnvironment = regManager.OpenSubKey("Environment", true);//打开MSSQLServer下的MSSQLServer
            regEnvironment.SetValue("path", this.richTextBox1.Text);//读取path的值

MessageBox.Show("修改成功");
            //下面利用发送系统消息,就不要重新启动计算机了
           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, 5000,(long)s);

}
        /// <summary>
        /// 重新启动计算机
        /// </summary>
        /// <param name="x"></param>
        /// <param name="y"></param>
        /// <returns></returns>
        [DllImport("user32.dll")]
        //主要API是这个,注意:必须声明为static extern
        private static extern int ExitWindowsEx(int x, int y);
        private void button1_Click(object sender, EventArgs e)
        {
            ExitWindowsEx(2,0);
        }
    }
}

 

C#读取“我的文档”等特殊系统路径及环境变量的更多相关文章

  1. 流操作text文件------读取、保存文档

    ************************************一.读取指定text文档中的内容:**************************************** 方法一. t ...

  2. P6 EPPM 16 R1 文档和帮助系统

    P6 EPPM 16 R1 文档和帮助系统 https://docs.oracle.com/cd/E74894_01/ http://docs.oracle.com/cd/E68202_01/clie ...

  3. Redis集群部署文档(Ubuntu15.10系统)

    Redis集群部署文档(Ubuntu15.10系统)(要让集群正常工作至少需要3个主节点,在这里我们要创建6个redis节点,其中三个为主节点,三个为从节点,对应的redis节点的ip和端口对应关系如 ...

  4. XmlReader和XElement组合之读取大型xml文档

    简介 在.NET framework 中存在大量操作xml数据的类库和api,但在.NET framework 3.5后我们的首选一般就是linq to xml. linq to xml操作xml数据 ...

  5. php创建读取 word.doc文档

    创建文档; <?php $html = "this is question"; for($i=1;$i<=3;$i++){ $word = new word(); $w ...

  6. Oracle PLSQL读取(解析)Excel文档

    http://www.itpub.net/thread-1921612-1-1.html !!!https://code.google.com/p/plsql-utils/ Introduction介 ...

  7. $ 用python处理Excel文档(1)——用xlrd模块读取xls/xlsx文档

    本文主要介绍xlrd模块读取Excel文档的基本用法,并以一个GDP数据的文档为例来进行操作. 1. 准备工作: 1. 安装xlrd:pip install xlrd 2. 准备数据集:从网上找到的1 ...

  8. 读取JDK API文档,并根据单词出现频率排序

    1,拿到 API 文档 登录 https://docs.oracle.com/javase/8/docs/api/ , 选中特定的类,然后 copy 其中的内容, 放入 TXT 文件中 , 2,读取T ...

  9. XWPFDocument创建和读取Office Word文档基础篇(一)

    注:有不正确的地方还望大神能够指出,抱拳了 老铁!   参考API:http://poi.apache.org/apidocs/org/apache/poi/xwpf/usermodel/XWPFDo ...

随机推荐

  1. delphi CopyFileProgressBar 拷贝文件显示进度条

    CopyFileProgressBar(pwidechar(ListBox1.Items.Strings[I]),pwidechar(NewDir+'\'+ExtractFileName(ListBo ...

  2. Android-Kotlin-单例模式

    先看一个案例,非单例模式的案例: 描述Dog对象: package cn.kotlin.kotlin_oop08 class Dog(var name:String, var color:String ...

  3. [转载]持续交付和DevOps的前世今生

    作者/分享人:乔梁,20年IT老兵,腾讯公司高级管理顾问,敏捷和精益开发专家,持续交付领域先行者.曾就职于百度,国内多个知名互联网公司的企业教练. 历年QCon技术大会的讲师和专题出品人. 这是一个新 ...

  4. HTML给table添加单线边框

    一般来说,给表格加边框都会出现不同的问题,以下是给表格加边框后展现比较好的方式 <style> table,table tr th, table tr td { border:1px so ...

  5. 一个docker容器中运行多个服务还是弄一堆docker容器运行?

    不建议直接在单个 Docker 容器中运行多个程序. 以 2017年 10 月18 日 Docker 官方支持 Kubernetes 为分水岭计算,Kubernetes 赢得容器编排之战的最终胜利已经 ...

  6. Quartz是一个任务调度

    这段时间做一个案子,用到每天定时处理事件,之前的解决思路是通过一个定时器轮询时间段,这样不能精准的在某个时间戳上执行动作.由于没有用过Quartz是一个任务调度,一直使用这个办法,今天通过同事提点,从 ...

  7. 脱壳系列—— 揭开so section加密的美丽外衣

    i春秋作家:HAI_ 0×00 前言 对so的加密,https://bbs.pediy.com/thread-191649.htm大神的帖子里已经很详细的说明了.当然加密不是我们研究的重点,如何搞掉这 ...

  8. day 38 jq 入门 学习(一)

    前情提要: jq是简化版本的js 可以把很多很复杂的js 提炼让前端代码更好写 一:jq的使用 <!DOCTYPE html> <html lang="en"&g ...

  9. POJ 2871

    #include<iostream> #include<stdio.h> #include<iomanip> using namespace std; int ma ...

  10. POJ 2405

    #include <iostream> #include <cmath> #include <iomanip> #define pi 3.1415926536 us ...