Windows环境变量编辑器 | Windows Environment Variables Editor

一个实用,简单,便捷的Windows环境变量编辑器(Windows Environment Variables Editor)。可以方便的编辑windows系统环境变量。

比那个老外写的 Rapid Environment Editor 方便的多,老外那个搞的有些太复杂了。。。  同样是C#写的。

20131025031134

可选择“系统变量” 或 “用户变量”, 忽略了用处不多的”进程变量”。

全部变量可以通过下拉框筛选。

20131025031219

环境变量列表:

列表变量条目上右键,会弹出菜单。20131025031338

新建变量:

20131025031412

新建系统变量时, 会检查时候已经存在。 如果存在考虑提示是否需改已存在的系统变量值。

20131025032910

编辑变量:20131025031442

有选项(默认)可以切分多个变量值为多行, 方便读改内容。编辑后确认, 会自动整合为无换行的一条变量值。

20131025031458

删除系统变量:

20131025032746

确认窗口, 以免误删。

20131025031533

个人作品, 欢迎建议。

参考:windows 环境变量 http://bohu.net/blog/177

下载地址: http://bohu.net/d/WindowsEnvironmentVariables.exe

Windows 驱动程序入门

驱动程序入门

从这里开始学习有关驱动程序的基本概念。

你应熟悉 C 编程语言,并且应了解函数指针、回调函数以及事件处理程序的理念。若要基于用户模式驱动程序框架 1.x 编写驱动程序,则应熟悉 C++ 和 COM。

什么是驱动程序?

 

为术语“驱动程序”给出单一的准确定义比较困难。就最基本的意义而言,驱动程序是一个软件组件,可让操作系统和设备彼此通信。例如,假设应用程序需要从设备中读取某些数据。应用程序会调用由操作系统实现的函数,操作系统会调用由驱动程序实现的函数。驱动程序(由设计和制造该设备的同一公司编写)了解如何与设备硬件通信以获取数据。当驱动程序从设备获取数据后,它会将数据返回到操作系统,操作系统将数据返回至应用程序。

图:显示应用程序、操作系统以及驱动程序

 

扩大定义

到目前为止,我们的说明采用以下几种方式进行简单化:

  • 并非所有驱动程序都必须由设计该设备的公司编写。在多种情形下,设备根据已发布的硬件标准来设计。这表示驱动程序可以由 Microsoft 编写,设备设计者无须提供驱动程序。
  • 并非所有驱动程序都直接与设备通信。对于给定的 I/O 请求(如从设备读取数据),通常有一些驱动程序(在堆栈中进行分层)参与该请求。可视化堆栈的传统方式是将第一个参与对象放在顶部,将最后一个参与对象放在底部,如此图所示。堆栈中的某些驱动程序可能通过将请求从一种格式转换至另一种格式来参与。这些驱动程序不会与设备直接通信;它们只操纵请求并将请求传递至堆栈下方的驱动程序。图:显示应用程序、操作系统、3 个驱动程序以及设备
  • 堆栈中直接与设备通信的一个驱动程序称为“函数驱动程序”;执行辅助处理的驱动程序称为“筛选器驱动程序”
  • 某些筛选器驱动程序遵守并记录有关 I/O 请求的信息,但不会主动参与这些请求。例如,某些筛选器驱动程序充当验证程序以确保堆栈中的其他驱动程序正确处理 I/O 请求。

我们可以扩大“驱动程序”的定义,方法是表示驱动程序为遵守或参与操作系统与设备之间通信的任一软件组件。

软件驱动程序

我们的扩大定义相当准确,但仍不完整,原因是某些驱动程序与任何硬件设备根本不关联。 例如,假设你需要编写可以访问核心操作系统数据结构的工具,这些结构仅可以由内核模式下运行的代码进行访问。可以通过将工具拆分成两个组件来执行该操作。第一个组件在用户模式下运行且提供用户界面。第二个组件在内核模式下运行且可以访问核心操作系统数据。在用户模式下运行的组件称为应用程序,在内核模式下运行的组件称为“软件驱动程序”。软件驱动程序与硬件设备不关联。有关处理器模式的详细信息,请参阅用户模式和内核模式

此图说明了与内核模式软件驱动程序通信的用户模式应用程序。

图:显示应用程序和软件驱动程序

其他说明

软件驱动程序始终在内核模式下运行。编写软件驱动程序的主要原因是获取对仅在内核模式下可用的受保护数据的访问权限。但是设备驱动程序不会始终需要访问内核模式数据和资源。因此某些设备驱动程序在用户模式下运行。

有一系列的驱动程序我们尚未提及,“总线驱动程序”。若要了解总线驱动程序,你需要了解设备节点和设备树。有关设备树、设备节点以及总线驱动程序的信息,请参阅设备节点和设备堆栈

到目前为止,我们的说明过度简化了“函数驱动程序”的定义。我们表示设备的函数驱动程序为堆栈中直接与设备通信的一个驱动程序。对于直接连接到外围组件互连 (PCI) 总线的设备而言,以上为真。PCI 设备的函数驱动程序获取映射到设备上端口和内存资源的地址。函数驱动程序通过写入这些地址直接与设备通信。但是在多种情形下,设备未直接连接到 PCI 总线。相反设备连接到的主机总线适配器连接到 PCI 总线。例如,USB toaster 连接到主机总线适配器(称为 USB 主控制器),该适配器连接到 PCI 总线。USB toaster 具有函数驱动程序,USB 主控制器也具有函数驱动程序。toaster 的函数驱动程序与 toaster 间接通信,方法是将请求发送至 USB 主控制器的函数驱动程序。然后,USB 主控制器的函数驱动程序与 USB 主控制器硬件直接通信,该硬件与 toaster 通信。

图:显示 USB toaster 驱动程序和 USB 主控制器驱动程序

 

选择驱动程序模型

Microsoft Windows 提供了多种驱动程序模型,你可以使用这些模型编写驱动程序。最佳驱动程序模型的选择策略取决于你计划编写的驱动程序类型。下文介绍了这些选项:

  • 设备函数驱动程序
  • 设备筛选器驱动程序
  • 软件驱动程序
  • 文件系统筛选器驱动程序
  • 文件系统驱动程序

有关各种类型驱动程序之间差异的介绍,请参阅什么是驱动程序?设备节点和设备堆栈。以下部分说明了如何为每种类型的驱动程序选择模型。

为设备函数驱动程序选择驱动程序模型

当你设计一个硬件设备时,首先要考虑的事项之一就是你是否需要编写函数驱动程序。提出下列问题:

是否可以完全避免编写驱动程序?
如果必须编写函数驱动程序,则最好使用哪个驱动程序模型?

若要回答这些问题,请确定设备的何处可以容纳设备和驱动程序技术中介绍的技术列表。参阅该特定技术的文档,以确定是否需要编写函数驱动程序以及了解哪些驱动程序模型可供设备使用。

某些个别技术具有微型驱动程序模型。在微型驱动程序模型中,设备驱动程序由两个部分组成:一个部分处理常规任务,另一部分处理设备特定的任务。通常,Microsoft 编写通用部分,设备制造商编写设备特定的部分。设备特定的部分具有多种名称,其中大部分名称都共享前缀“微型”。以下是微型驱动程序模型中使用的一些名称:

  • 显示器微型端口驱动程序
  • 音频微型端口驱动程序
  • 电池微型类驱动程序
  • 蓝牙协议驱动程序
  • HID 微型驱动程序
  • WIA 微型驱动程序
  • NDIS 微型端口驱动程序
  • 存储器微型端口驱动程序
  • 流微型驱动程序

有关微型驱动程序模型的概述,请参阅微型驱动程序和驱动程序对

并非设备和驱动程序技术中列出的每项技术都有专用的微型驱动程序模型。特定技术的文档可能会建议你使用内核模式驱动程序框架 (KMDF);其他技术的文档可能会建议你使用用户模式驱动程序框架 (UMDF)。关键点是你应从研究特定设备技术的文档开始。如果你的设备技术具有微型驱动程序模型,则必须使用微型驱动程序模型。否则就遵循技术特定的文档中有关是使用 UMDF、KMDF 还是 Windows 驱动程序模型 (WDM) 的建议。

为设备筛选器驱动程序选择驱动程序模型

一些驱动程序频繁参与单个 I/O 请求(如从设备读取数据)。驱动程序在堆栈中进行分层,并且可视化堆栈的常规方法是将第一个驱动程序放在顶部,将最后一个驱动程序放在底部。堆栈具有一个函数驱动程序并且还可以具有筛选器驱动程序。有关函数驱动程序和筛选器驱动程序的介绍,请参阅什么是驱动程序?设备节点和设备堆栈

如果你准备为设备编写筛选器驱动程序,则确定设备的何处可以容纳设备和驱动程序技术中介绍的技术列表。查看特定设备技术的文档是否有关于选择筛选器驱动程序模型的任何指南。如果设备技术的文档未提供此指南,则首先考虑使用 UMDF 作为驱动程序模型。如果筛选器驱动程序需要访问的数据结构无法通过 UMDF 获取,则考虑使用 KMDF 作为驱动程序模型。在极端少见的情形中,驱动程序需要访问的数据结构无法通过 KMDF 获取,则使用 WDM 作为驱动程序模型。

为软件驱动程序选择驱动程序模型

未与设备关联的驱动程序称为“软件驱动程序”。有关软件驱动程序的介绍,请参阅什么是驱动程序?主题。软件驱动程序很有用,原因是这些驱动程序可以在内核模式下运行,这样为其提供了受保护操作系统数据的访问权限。有关处理器模式的信息,请参阅用户模式和内核模式

有关软件驱动程序,你的两个选项为 KMDF 和旧的 Windows NT 驱动程序模型。使用 KMDF 和旧的 Windows NT 模型,你可以在编写驱动程序时无须考虑即插即用 (PnP) 和电源管理。你可以改为专心于驱动程序的首要任务上。使用 KMDF,你不必考虑 PnP 和电源,因为框架会为你处理 PnP 和电源。使用旧的 Windows NT 模型,你不必考虑 PnP 和电源,原因是旧的驱动程序在与 PnP 和电源管理完全无关的环境中运行。

我们的建议是使用 KMDF,尤其是当你已熟悉 KMDF 时。如果你希望驱动程序与 PnP 和电源管理完全无关,则使用旧的 Windows NT 模型。如果你需要编写注意到电源转换或 PnP 事件的软件,则不能使用旧的 Windows NT 模型;必须使用 KMDF。

Note  在极少情形中,你需要编写注意到 PnP 或电源事件的软件驱动程序,并且驱动程序需要访问无法通过 KMDF 获取的数据,则必须使用 WDM。

为文件系统筛选器驱动程序选择驱动程序模型

有关为文件系统筛选器驱动程序选择模型的帮助,请参阅“文件系统微过滤驱动程序”和文件系统筛选器驱动程序

为文件系统驱动程序选择驱动程序模型

有关为文件系统驱动程序选择模型的帮助,请参阅文件系统微过滤驱动程序。+

 

编写第一个驱动程序

提供了三个练习,指导你完成编写和构建小型驱动程序的整个过程。第一个练习基于用户模式驱动程序框架 (UMDF),其他两个练习基于内核模式驱动程序框架 (KMDF)。

尽管因为稳定性和可靠性的缘故 UMDF 为首选模型,但 KMDF 提供了一个有吸引力的机会,可以编写非常小的 Hello World 驱动程序。使用 KMDF,你可以编写非常简短的驱动程序,仅实现两个函数。

这些练习之间彼此独立,因此你可以采用任何顺序选择仅做其中一个练习或所有练习。 要点是获取一些有关驱动程序代码编写和构建的早期实例体验。

 

国际化域名IDN (Internationalized Domain Names) 转换

将域名国际化 IDN (internationalized domain name) 标准编码的域名标签的子字符串解码为一个 Unicode 字符串(Punycode). 或者将一个国际化域名字符串(Punycode )转换为符合 IDN 标准的域名
例:
Bücher.ch --> xn--bcher-kva.ch |
новини.com --> xn--b1amarcd.com |
统计局.中国 --> xn--dgtp91f7xi.xn--fiqs8s |
xn--j6w193g.xn--fiqs8s --> 香港.中国

代码段:

IDNA  >> Punycode

IdnMapping idn = new IdnMapping();
string international = idn.GetAscii(yourDomain, 0, yourDomain.Length);

Punycode  >> IDNA

>IdnMapping idn = new IdnMapping();
string nonInternational = idn.GetUnicode(yourDomain, 0, yourDomain.Length);

 

下载文件 : IDN Converter

 

在C#中调用 VB.Net 中的 IsSingleInstance 实现只运行单个实例的应用程序

<<Windows Forms 2.0 Programming, 2nd Edition>>   –  Single-Instance Applications 这一章中, 学到了调用 VB.Net 中的 IsSingleInstance, 为 C# WinForm 添加只运行应用程序的单个实例 ( Single Instance Application). 是个好方法!

该方法显然从易用性上便捷与 Mutex 和 Process 这两种只运行单个应用程序实例的方法.

 

Single Instance 概念:

从.NET 2.0起,提供了WindowsFormsApplicationBase类来简化Windows应用程序编程,如果您是开发人员会感到感到奇怪,WindowsFormsApplicationBase类不在System.Windows.Forms 命名空间中而是属于Microsoft.VisualBasic.ApplicationServices 命名空间,也许这是作为VB.NET开发人员的优先好处吧。该类对应的程序集为Microsoft.VisualBasic.dll,不过该程序集包含在.NET框架中一起发布,如果要引用该程序集,在部署上不存在额外操作。

WindowsFormsApplicationBase类实现了类似于Application类的一些功能,不过该类还包含一些简化Windows Forms应用程序开发的接口,下面来简单了解一下。WindowsFormsApplicationBase类实现了对单实例应用程序的支持,通过设置IsSingleInstance 属性为True以及重写OnStartupNextInstance方法可以简洁的实现。

 

实现

在 Program.cs – Main 方法

1. 项目中引用VB.Net 的DLL – Microsoft.VisualBasic.DLL,

Program.cs

using Microsoft.VisualBasic.ApplicationServices;

2. 在Program.cs中增加一个类

Program.cs

public sealed class SingleInstanceApplication : WindowsFormsApplicationBase
{
    public SingleInstanceApplication()
    {
        base.IsSingleInstance = true;
        base.ShutdownStyle = ShutdownMode.AfterMainFormCloses;
    }

    protected override void OnCreateMainForm()
    {
        base.MainForm = new MainForm();
    }

    protected override void OnStartupNextInstance(StartupNextInstanceEventArgs e)
    {
        base.OnStartupNextInstance(e);
        base.MainForm.Activate();
    }
}

 

3. 修改原 Application.Run(new MainForm()); 方法为:

//添加运行单进程程序
SingleInstanceApplication application = new SingleInstanceApplication();
application.Run(args);

 

SingleInstanceApplication类继承自WindowsFormsApplicationBase,在构造函数中设置为单实例模式,同时设置在主窗体关闭后退出应用程序。在继承类中,OnCreateMainForm方法被重写用来创建主窗体,如果要保证应用程序单一实例运行,还需要重写OnStartupNextInstance方法,在该应用程序的下一个应用程序实例启动时,OnStartupNextInstance方法会得到执行,在上面的实现代码中,调用基类方法同时激活主窗口。

 

windows 环境变量

Getting and setting environment variables

The variables can be used both in scripts and on the command line. They are usually referenced by putting special symbols in front of or around the variable name. For instance, to display the user home directory, in most scripting environments, the user has to type:

echo $HOME

On DOS, OS/2 or Windows systems, the user has to type this:

echo %HOME%

In Windows PowerShell, the user has to type this:

Write-Output $HOME

DOS, OS/2 and Windows (Command Prompt)

In DOS, OS/2 and Windows, the set command without any arguments displays all environment variables along with their values.

To set a variable to a particular value, use:

set VARIABLE=value

However, this is temporary. Permanent change to the environment variable can be achieved through editing the registry (not recommended for novices) and using the Windows Resource Kit application setx.exe. With the introduction of Windows Vista, the setx command became part of Windows.

Users of the Windows GUI can manipulate variables via <Control Panel:System:Advanced:Environment Variables>; through the Windows Registry this is done changing the values under HKCU\Environment (for user specific variables) and HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment (for System variables).

To set a variable whose name is in another variable:

set %VARNAME%=value

This feature allows certain interesting applications. For example, a uni-dimensional array of elements (vector) may be generated this way:

set VECTOR[%I%]=value of element subscript %I%

:MkVec
set VECNAME=%1
set i=0
:loop
    shift
    if "%1" == "" goto exitloop
    set /a i+=1
    set %VECNAME%[%i%]=%1
    goto loop
:exitloop
exit /B %i%

call :MkVec DOWNAME=Monday Tuesday Wednesday Thursday Friday Saturday Sunday

To see the current value of a particular variable, use:

echo %VARIABLE%

or

set VARIABLE

Note: Please take note that doing so will print out all variables beginning with ‘VARIABLE’. Another example is:

C:\> set p
Path=c:\.. ..
PATHEXT=.COM;.EXE;.BAT;
PROCESSOR_ARCHITECTURE=.. ..
PROCESSOR_IDENTIFIER=x8..
PROCESSOR_LEVEL=6..
PROCESSOR_REVISION=1706..
ProgramFiles=C:\Program.. .
PROMPT=$P$G

To see the value of an array element a double expansion is required: one for the subscript value and an additional expansion for the array element. This may be achieved via Delayed !VARIABLE! Expansion this way:

set DOW=value of Day of Week (1..7)
echo !DOWNAME[%DOW%]!

To delete a variable, the following command is used:

set VARIABLE=

Windows PowerShell

To set a system variable:

Set-Content -Path Env:VARIABLE -value value
$Env:VARIABLE = value # alternate form

Examples of DOS environment variables

%COMSPEC%

This variable contains the full path to the command processor, command.com.

%PATH%

This variable contains a semicolon-delimited list of directories in which the command interpreter will search for executable files. Equivalent to the Unix $PATH variable (although note that PATH on Windows additionally performs the same task as LD_LIBRARY_PATH on Unix-like systems). Note that %PATH% can also be set like this PATH=c:\dos; where SET isn’t required.

%TEMP% and %TMP%

These variables contain the path to the directory where temporary files should be stored.

Examples from Microsoft Windows

Discrete value variables

These variables generally expand to discrete values, such as the current working directory, the current date, or a random number. Some of these are true environment variables and will be expanded by all functions that handle environment variables. Others, like %CD% simply look like environment variables and will only be expanded by some functions and shells. They are not case sensitive.

%CD%

This variable points to the current directory. Equivalent to the output of the command cd when called without arguments.

%DATE%

This variable expands to the current date. The date is displayed according to the current user’s date format preferences.

The following is a way of reformatting the date and time for use in file copies. The example assumes UK format of day month year and the time is set for a 24 hour clock.

@echo off
echo %DATE% %TIME%
for /F "tokens=1-3 delims=/" %%a in ("%DATE%") do set MTH=%%a& set DAY=%%b& set YR=%%c
for /F "tokens=1-3 delims=:." %%a in ("%TIME%") do set HR=%%a& set MIN=%%b& set SEC=%%c
if "%HR:~0,1%"==" " set HR=0%HR:~1,1%
set MYDATE=%YR%%MTH%%DAY%-%HR%%MIN%%SEC%
echo %MYDATE%
%ERRORLEVEL%

This variable points to the current error level. If there was an error in the previous command, it is checked against this.

%RANDOM%

This variable returns a random number between 0 and 32767.

%TIME%

This variable points to the current time. The time is displayed according to the current user’s time format preferences.

System path variables

These variables refer to locations of critical operating system resources, and as such generally are not user-dependent.

%AppData%

Contains the full path to the Application Data directory of the logged-in user. Does not work on Windows NT 4.0 SP6 UK.

%LOCALAPPDATA%

This variable is the temporary files of Applications. Its uses include storing of Desktop Themes, Windows Error Reporting, Caching and profiles of web browsers.

%ComSpec%

This variable contains the full path to the command processor; on Windows NT based operating systems this is cmd.exe, while on Windows 9x and ME it is the DOS command processor, COMMAND.COM.

%PATH%

This variable contains a semicolon-delimited (do not put spaces in between) list of directories in which the command interpreter will search for an executable file that matches the given command. Equivalent to the Unix $PATH variable.

%ProgramFiles%

This variable points to Program Files directory, which stores all the installed program of Windows and others. The default on English-language systems is C:\Program Files. In 64-bit editions of Windows (XP, 2003, Vista), there are also %ProgramFiles(x86)% which defaults to C:\Program Files (x86) and %ProgramW6432% which defaults to C:\Program Files. The %ProgramFiles% itself depends on whether the process requesting the environment variable is itself 32-bit or 64-bit (this is caused by Windows-on-Windows 64-bit redirection).

%CommonProgramFiles%

This variable points to Common Files directory. The default is C:\Program Files\Common Files.

%SystemDrive%

The %SystemDrive% variable is a special system-wide environment variable found on Microsoft Windows NT and its derivatives. Its value is the drive upon which the system directory was placed. Also see next item.

The value of %SystemDrive% is in most cases C:.

%SystemRoot%

The %SystemRoot% variable is a special system-wide environment variable found on Microsoft Windows NT and its derivatives. Its value is the location of the system directory, including the drive and path.

The drive is the same as %SystemDrive% and the default path on a clean installation depends upon the version of the operating system. By default, on a clean installation:

  • Windows NT 5.1 (Windows XP) and newer versions use \WINDOWS
  • Windows NT 5.0 (Windows 2000), Windows NT 4.0 and Windows NT 3.1 use \WINNT
  • Windows NT 3.5x uses \WINNT35
  • Windows NT 4.0 Terminal Server use \WTSRV
%WinDir%

This variable points to the Windows directory (on Windows NT-based operating systems it is identical to the %SystemRoot% variable, above). If the System is on drive C: then the default values are:

Note that Windows NT 4 Terminal Server Edition by default installs to C:\WTSRV.

User management variables

These variables store information related to resources and settings owned by various user profiles within the system. As a general rule, these variables do not refer to critical system resources or locations that are necessary for the OS to run.

%AllUsersProfile% (%PROGRAMDATA% for Windows Vista, Windows 7)

The %AllUsersProfile%(%PROGRAMDATA%) variable expands to the full path to the All Users profile directory. This profile contains resources and settings that are used by all system accounts. Shortcut links copied to the All Users’ Start menu or Desktop directories will appear in every user’s Start menu or Desktop, respectively.

%UserDomain%

The variable holds the name of the Workgroup or Windows Domain to which the current user belongs. The related variable, %LOGONSERVER%, holds the hostname of the server that authenticated the current user’s logon credentials (name and password). For Home PCs, and PCs in a Workgroup, the authenticating server is usually the PC itself. For PCs in a Windows Domain, the authenticating server is a domain controller (a primary domain controller, or PDC, in Windows NT 4-based domains).

%UserProfile%

The %UserProfile% variable is a special system-wide environment variable found on Microsoft Windows NT and its derivatives. Its value is the location of the current user’s profile directory, in which is found that user’s HKCU registry hive (NTUSER).

Users can also use the %USERNAME% variable to determine the active users login identification.

Windows GUI forced variable expansion

In certain cases it is not possible to create file paths containing environment variables using the Windows GUI, and it is necessary to fight with the user interface to make things work as intended.

  • In Windows 7, a shortcut may not contain the variable %USERNAME% in unexpanded form. Trying to create shortcut to \\server\share\accounts\%USERNAME% or C:\users\%USERNAME% will be silently changed to replace %USERNAME% with the account name of the currently logged-in user, when the OK button is pressed on the shortcut properties.
    • This can only be overridden if the %USERNAME% variable is part of a parameter to some other program in the shortcut. For example, %SYSTEMROOT%\Explorer.exe C:\Users\%USERNAME% is not expanded when OK is clicked, but this shortcut is treated as unsafe and displays a warning when opened.
  • In Group Policy Management on Server 2008 R2, a profile directory can not be redirected to a custom directory hierarchy. For example, the desktop can not be redirected to \\server\share\accounts\%USERNAME%\custom\path\desktop. Upon pressing OK, this is silently changed to “Create a directory for each user in the root path” with the path \\server\share\accounts\ pointing to “\username\desktop”.
    • This behavior can only be overridden if the path contains a variable or drive letter that is not currently resolvable at the time of editing the GPO. For example if a mapping for drive Z: does not exist on the server, then the path Z:\directory\%username%\CustomTarget is not expanded when OK is selected.
  • A domain user account may not contain a profile path or home directory path containing an unexpanded %USERNAME% variable. Upon clicking OK, this is silently replaced with the user’s account name.
    • This causes problems for new user creation that is performed by copying an existing user account, if there are additional directories listed after the username in the path. For a pre-existing account with a profile path of \server\share\accounts\DomainUser\profile the Microsoft Management Console doesn’t know which part of the path contains the previous user’s name and doesn’t change the path during the copy, resulting in the new account pointing to the other account’s profile/home paths. The profile/home paths must be manually re-edited to point to the correct location.

Default Values on Microsoft Windows

Variable Windows XP Windows Vista/7
 %ALLUSERSPROFILE% C:\Documents and Settings\All Users C:\ProgramData
 %APPDATA% C:\Documents and Settings\{username}\Application Data C:\Users\{username}\AppData\Roaming
 %COMPUTERNAME% {computername} {computername}
 %COMMONPROGRAMFILES% C:\Program Files\Common Files C:\Program Files\Common Files
 %COMMONPROGRAMFILES(x86)% C:\Program Files (x86)\Common Files (only in 64-bit version) C:\Program Files (x86)\Common Files (only in 64-bit version)
 %COMSPEC% C:\Windows\System32\cmd.exe C:\Windows\System32\cmd.exe
 %HOMEDRIVE% C: C:
 %HOMEPATH% \Documents and Settings\{username} \Users\{username}
 %LOCALAPPDATA% C:\Users\{username}\AppData\Local
 %LOGONSERVER% \\{domain_logon_server} \\{domain_logon_server}
 %PATH% C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;{plus program paths} C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;{plus program paths}
 %PATHEXT% .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.WSF;.WSH .com;.exe;.bat;.cmd;.vbs;.vbe;.js;.jse;.wsf;.wsh;.msc
 %PROGRAMDATA%  %SystemDrive%\ProgramData
 %PROGRAMFILES%  %SystemDrive%\Program Files  %SystemDrive%\Program Files
 %PROGRAMFILES(X86)%  %SystemDrive%\Program Files (x86) (only in 64-bit version)  %SystemDrive%\Program Files (x86) (only in 64-bit version)
 %PROMPT% Code for current command prompt format. Code is usually $P$G Code for current command prompt format. Code is usually $P$G
 %PSModulePath%  %SystemRoot%\system32\WindowsPowerShell\v1.0\Modules\
 %PUBLIC%  %SystemDrive%\Users\Public
{Drive}:\$Recycle.Bin C:\Recycle.Bin C:\$Recycle.Bin
 %SystemDrive% C: C:
 %SystemRoot% The Windows directory, usually C:\Windows, formerly C:\WINNT  %SystemDrive%\Windows
 %TEMP% and %TMP%  %SystemDrive%\Documents and Settings\{username}\Local Settings\Temp  %SystemDrive%\Users\{username}\AppData\Local\Temp
 %USERDOMAIN% {userdomain} {userdomain}
 %USERNAME% {username} {username}
 %USERPROFILE%  %SystemDrive%\Documents and Settings\{username}  %SystemDrive%\Users\{username}
 %WINDIR%  %SystemDrive%\Windows  %SystemDrive%\Windows

In this list, there is no environment variable that refers to the location of the user’s My Documents directory, so there is no standard method for setting a program’s home directory to be the My Documents directory.

C# 多线程操作整理 (System.Threading)

Thread 类

创建并控制线程,设置其优先级并获取其状态。

命名空间:System.Threading 程序集:mscorlib(在 mscorlib.dll 中)

概述与概念

C#支持通过多线程并行地执行代码,一个线程有它独立的执行路径,能够与其它的线程同时地运行。一个C#程序开始于一个单线程,这个单线程是被CLR和操作系统(也称为“主线程”)自动创建的,并具有多线程创建额外的线程。

1.使用线程的情况

  • ①.程序需要执行和两个和多个任务
  • ②.程序要等待某事件的发生:例如用户输入、文件操作、网络操作和搜索
  • ③.后台程序

2.多线程的并发执行 如果有多个线程在执行,单CPU只有一个,到底执行的哪个?

  • ①.如果一个线程连续占用CPU资源时间过长,其它的资源得不到执行,      则系统会强制的切换执行其它线程。(强制剥夺)
  • ②.如果一个线程没事可做、CPU可执行其它线程。(主动放弃)
  • ③.这是由操作系统的调度机制决定的,不同的操作系统调度机制不一样。    一般无法精确的预料多线程的执行顺序,在程序设计的时候应特别注意

3.创建并启动线程

ThreadStart 线程启动委托名=new ThreadStart(方法名);

Thread 线程实例名=new Thread(线程启动委托名); 线程实例名.Start();

4.终止线程

  • ①.线程实例名.Abort();用此方法的后果是不可恢复的终止线程。
  • ②.线程实例名.Interrupt();中断后可恢复

5.休眠线程

  • ①.线程实例名.Sleep();     当线程Sleep时,系统就立即退出执行队列一段时间,当睡眠结束时,系统会产生一个时钟中断,从而     使线程回到执行队列中,从而恢复线程的执行。

6.挂起/恢复线程

  • ①.线程实例名.Suspend();挂起     与线程休眠不同,线程的挂起不会使线程立即停止执行,直到线程到达安全点之后它才可以将该线程挂起,如果线程尚未启动或已经停止,则它将不能挂起。
  • ②.线程实例名.Resume();恢复      将使一个线程跳出挂起状态并使该线程继续执行。     一个线程不能对另一个线程调用Sleep() ,但是一个线程可以对另一个线程调用Suspend()。     还可以使用许多其它的方式来阻塞线程。例如,可以通过调用 Thread.Join 使一个线程等待另一个线程 (子线程)停止。使用Monitor.Wait使一个线程等待访问一个同步对象。

7.串行化线程

  • ①.线程实例名.jion();     例如在主线程中插入t.jion();      主线程执行到这条语句后,主线程(当前线程)立即进入阻塞状态.直到t运行完后阻塞状态才解除。相当于把t的任务插入或串联到主线程中,把两条线索串联成一条线索

8.线程的锁定机制 线程的锁定机制可以保证每次只有一个线程可以访问共享资源。 使用关键字lock

  • ①.lock语句的语法      lock(对象引用)语句块;
  • ②.lock语句的功能      当对象被lock 锁定时,访问该线程的其它线程会进入等待的状态。
  • ③.对象锁机制保证了对象访问的完整性:只有一个线程完成操作后,其它的线程才能进行操作。
  • ④.一般情况下,当一个线程写某个变量,而同时可能有其它的线程读或写这个变量时,为了保持数据的一 致性应该使用锁定机制。
  • ⑤.线程的安全性      线程安全性就是保护的类的成员和代码的安全,从而使他们不会同时被几个线程中断,使用锁定机制。
  • ⑥.多线程公用一个对象时,就不应该使用lock关键字了,这里Monitor,Monitor提供了使线程共享资源的方 案。 Monitor类可以锁定一个对象,一个线程只有得到这把锁才可以对该对象进行操作。 如: Monitor.Enter(obj);
    Monitor.Exit(obj);
  • ⑦.临界区和锁 当谈论多线程应用程序的时候,首先应该想到的就是并发性问题。尽管这对于同时执行多个任务的程序是很有用的,但通常都是危险的。为了解决这个问题,在C#中提出了临界区和锁的概念。在程序设计中,临界区是一块在任何时候只能有一个进程进入的区域。在C#中通过语句lock来声明临界区。lock声明后面的代码,不管是以行还是一块代码,在同一时间最多只能有一个进程执行。

9.线程的优先级具有不可靠性,就是说不能用优先级来控制线程的执行顺序。

10.后台线程

  • ①.什么是后台线程?比起应用程序的主图形用户界面(GUI)线程来说,这些线程以较低的优先权在不同的过程中运行着。对于不能立即执行结束, 又不想一直等待的任务,后台线程能很好的胜任。在C#中,把线程对象的  IsBackground属性设为true,该线程即为后台线程。    后台线程跟前台线程只有一个区别,那就是后台线程不妨碍程序的终止。一旦一个进程所有的前台线程都终止后,CLR将通过调用任意一个存活中的后台进程的Abort()方法来彻底终止进程。注意:后台线程不能直接操作所在进程之外的数据引用。
  • ②.怎样与后台线程通讯?运用MethodInvoker委派实体。也可在初始化(构造函数)中加入下面一句即可实现通讯:

Control.CheckForIllegalCrossThreadCalls = False;

要使用MethodInvoker委派,需要三个条件:

  •   a.一个创建委派的后台线程
Thread thread=new Thread(new ThreadStart(Run));

thread.IsBackground=true;  //把Thread设为后台线程

thread.Start();
  •   b.一个用作后台线程与前台可视化单元的接口的类级方法
 public void Run()
        {
            int count = 0;
            try
            {
                MethodInvoker mi = new MethodInvoker(this.UpdateLabel);
                //创建一个委托,UpdateLabel是该委托所托管的代码,必须是声明为void 且不接受任何参数的任何方法。
                while (true)
                {
                    count++;
                    //this.Invoke(mi);//同步执行委托
                    this.BeginInvoke(mi);//异步执行委托
                    Thread.Sleep(500);
                }
            }
            catch (ThreadInterruptedException e)
            {
                Console.WriteLine("Interruption Exception in Thread:{0}", e);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception in Thread:{0}", ex);
            }
        }
  •   c.一个应用程序中可以更新的可视化单元
public void UpdateLabel()
{     
    label1.Text=count.ToString();   
}

.NET Windows Forms C# 线程中的全局异常处理

异常处理

任何线程创建范围内try/catch/finally块,当线程开始执行便不再与其有任何关系。考虑下面的程序:

public static void Main() {
try {
       new Thread (Go).Start();
}
catch (Exception ex) {
       // 不会在这得到异常
       Console.WriteLine ("Exception!");
}

static void Go() { throw null; }
}

这里try/catch语句一点用也没有,新创建的线程将引发NullReferenceException异常。当你考虑到每个线程有独立的执行路径的时候,便知道这行为是有道理的,补救方法是在线程处理的方法内加入他们自己的异常处理:

public static void Main() {
      new Thread (Go).Start();
}

static void Go() {
try {
       ...
       throw null;         // 这个异常在下面会被捕捉到
       ...
}
catch (Exception ex) {
       记录异常日志,并且或通知另一个线程
       我们发生错误
       ...
}

从.NET 2.0开始,任何线程内的未处理的异常都将导致整个程序关闭,这意味着忽略异常不再是一个选项了。因此为了避免由未处理异常引起的程序崩溃,try/catch块需要出现在每个线程进入的方法内,至少要在产品程序中应该如此。对于经常使用“全局”异常处理的Windows Forms程序员来说,这可能有点麻烦,像下面这样:

using System;
using System.Threading;
using System.Windows.Forms;

static class Program {
static void Main() {
       Application.ThreadException += HandleError;
       Application.Run (new MainForm());
}

static void HandleError (object sender, ThreadExceptionEventArgs e) {
       记录异常或者退出程序或者继续运行...
}
}

Application.ThreadException事件在异常被抛出时触发,以一个Windows信息(比如:键盘,鼠标活着 “paint” 等信息)的方式,简言之,一个Windows Forms程序的几乎所有代码。虽然这看起来很完美,它使人产生一种虚假的安全感——所有的异常都被中央异常处理捕捉到了。由工作线程抛出的异常便是一个没有被Application.ThreadException捕捉到的很好的例外。(在Main方法中的代码,包括构造器的形式,在Windows信息开始前先执行)

.NET framework为全局异常处理提供了一个更低级别的事件:AppDomain.UnhandledException,这个事件在任何类型的程序(有或没有用户界面)的任何线程有任何未处理的异常触发。尽管它提供了好的不得已的异常处理解决机制,但是这不意味着这能保证程序不崩溃,也不意味着能取消.NET异常对话框。

c# 获取HTTP headers 以及获取页面title

在写一个工具, 其中一个功能是检测收集服务器的一些信息, 需要在一个操作中取到HTTP headers 信息和 页面的标题(title).

尝试了WebRequest,WebResponse和 HttpWebRequest,HttpWebResponse. 研究他们的不同, 有Http的提供 了对无Http类的 HTTP 特定方法的实现. 关键似乎找不到我的要求”在一次操作中”完成获取到HTTP headers 和 title.

最后突然看到了一段国外代码中用到WebClient, 虽然功能不尽相同, 但又多了一点思路.  进行一翻测试, 发现WebClient十分简便好用, 代码量也骤减. 虽然效率可能会略慢一些,但是做到了一次调用, 取到headers 和 title.

代码如下:

//方法函数		
		/// <summary>
		/// 返回 HTTP headers.
		/// </summary>
		/// <param name="Url">地址</param>
		/// <returns>headers的列表</returns>
		public Dictionary<string, string> GetHTTPResponseHeaders(string url)
		{
		    Dictionary<string, string> HeaderList = new Dictionary<string, string>();

            WebClient x = new WebClient();
            x.Headers.Set("Timeout", "6000"); //超时设置6秒
            string source = x.DownloadString(url);

            //用正则表达式取页面标题
            string title = Regex.Match(source, @"<titleb[^>]*>s*(?<Title>[sS]*?)</title>", RegexOptions.IgnoreCase).Groups["Title"].Value;
            HeaderList.Add("Address", url); //加入地址
            HeaderList.Add("Title", title); //加入页面标题

            foreach (string HeaderKey in x.ResponseHeaders)
                HeaderList.Add(HeaderKey, x.ResponseHeaders[HeaderKey]);

		    return HeaderList;
		}

//调用
		void Button2Click(object sender, EventArgs e)
		{
			Dictionary<string, string> Headers = GetHTTPResponseHeaders("http://www.bohu.cn/");

			foreach (string HeaderKey in Headers.Keys) 
			    textBox5.Text += HeaderKey+" : "+Headers[HeaderKey]+"rn";
		}