.NET tip: Getting the Users Home, Temp or My Documents Directory by Charlie Calvert

CALVERT 立即下载
.NET tip: Getting the Users Home, Temp or My Documents Directory by Charlie Calvert
Rating: Rating is 3.5 - 4.5     Ratings: 67     Rate it
Abstract: It was not immediately obvious to me how to retrieve commonly used directories when using .NET. The examples in this article outline how these simple tasks are performed. 

by Charlie Calvert

A common need for programmers is to get the users home directory and other commonly used directories. In .NET, this involves using a combination of the Environment.SpecialFolders enumeration, and the Environment.GetEnvironmentVariable() function. The code in this article is written in C#, but it should be easy to translate it into Pascal code.

Special Folders

Here is the Environment.SpecialFolder enumeration:

	Environment.SpecialFolder.ApplicationData
Environment.SpecialFolder.System
Environment.SpecialFolder.CommonApplicationData
Environment.SpecialFolder.CommonProgramFiles
Environment.SpecialFolder.Cookies
Environment.SpecialFolder.Desktop
Environment.SpecialFolder.DesktopDirectory
Environment.SpecialFolder.Favorites
Environment.SpecialFolder.History
Environment.SpecialFolder.InternetCache
Environment.SpecialFolder.LocalApplicationData
Environment.SpecialFolder.MyComputer
Environment.SpecialFolder.MyMusic
Environment.SpecialFolder.MyPictures
Environment.SpecialFolder.Personal
Environment.SpecialFolder.ProgramFiles
Environment.SpecialFolder.Programs
Environment.SpecialFolder.Recent
Environment.SpecialFolder.SendTo
Environment.SpecialFolder.StartMenu

Here is how to use this enumeration:

 String PersonalFolder = 
Environment.GetFolderPath(Environment.SpecialFolder.Personal);

After executing this code, the variable PersonalFolder should contain the value of your My Documents directory.

Special Folders, Integer value of Enum, Dir on My System

In Listing 1 you see the values of all the special folders on my system. Note that this enumeration is not sequential. In particular, the integer value for the first member of the enumeration in .NET 1.1 is 0, the next is 2, then 5, then 6, etc. I got these values by writing this code: int i = (int)sp. If someone sees a pattern here, let me know!

Listing 1: The values of the SpecialFolder enumeration on my system. The number in the first column is the integer value of the particular SpecialFolder member shown in the second column.

0	Desktop			C:/Documents and Settings/Charlie/Desktop
2 Programs C:/Documents and Settings/Charlie/Start Menu/Programs
5 Personal D:/documents
6 Favorites C:/Documents and Settings/Charlie/Favorites
8 Recent C:/Documents and Settings/Charlie/Recent
9 SendTo C:/Documents and Settings/Charlie/SendTo
11 StartMenu C:/Documents and Settings/Charlie/Start Menu
13 MyMusic D:/documents/My Music
16 DesktopDirectory C:/Documents and Settings/Charlie/Desktop
17 MyComputer
26 ApplicationData C:/Documents and Settings/Charlie/Application Data
28 LocalApplicationData C:/Documents and Settings/Charlie/Local Settings/Application Data
32 InternetCache C:/Documents and Settings/Charlie/Local Settings/Temporary Internet Files
33 Cookies C:/Documents and Settings/Charlie/Cookies
34 History C:/Documents and Settings/Charlie/Local Settings/History
35 CommonApplicationData C:/Documents and Settings/All Users/Application Data
37 System C:/WINDOWS/System32
38 ProgramFiles C:/Program Files
39 MyPictures D:/documents/My Pictures
43 CommonProgramFiles C:/Program FilesCommon Files

Listing 2 shows the code for getting the values found in the previous listing. Note the use of the IList interface to access the list of strings stored in a ListBox. Becoming comfortable with interfaces is one of the core tasks for programmers migrating from Win32 to .NET. Java programmers should already be familiar with this paradigm.

Listing 2: The code for retrieving the values displayed in Listing 1.

	private static void ShowSpecialFolder(Environment.SpecialFolder sp, IList list)
{
int i = (int)sp;
String S1 = String.Format("{1} {0} {2} {0}{0}{0} {3}", '/t', i,
sp.ToString(), Environment.GetFolderPath(sp));
list.Add(S1);
}

public static IList GetAllSpecialFolders(IList list)
{
ShowSpecialFolder(Environment.SpecialFolder.ApplicationData, list);
ShowSpecialFolder(Environment.SpecialFolder.System, list);
ShowSpecialFolder(Environment.SpecialFolder.CommonApplicationData, list);
ShowSpecialFolder(Environment.SpecialFolder.CommonProgramFiles, list);
ShowSpecialFolder(Environment.SpecialFolder.Cookies, list);
ShowSpecialFolder(Environment.SpecialFolder.Desktop, list);
ShowSpecialFolder(Environment.SpecialFolder.DesktopDirectory, list);
ShowSpecialFolder(Environment.SpecialFolder.Favorites, list);
ShowSpecialFolder(Environment.SpecialFolder.History, list);
ShowSpecialFolder(Environment.SpecialFolder.InternetCache, list);
ShowSpecialFolder(Environment.SpecialFolder.LocalApplicationData, list);
ShowSpecialFolder(Environment.SpecialFolder.MyComputer, list);
ShowSpecialFolder(Environment.SpecialFolder.MyMusic, list);
ShowSpecialFolder(Environment.SpecialFolder.MyPictures, list);
ShowSpecialFolder(Environment.SpecialFolder.Personal, list);
ShowSpecialFolder(Environment.SpecialFolder.ProgramFiles, list);
ShowSpecialFolder(Environment.SpecialFolder.Programs, list);
ShowSpecialFolder(Environment.SpecialFolder.Recent, list);
ShowSpecialFolder(Environment.SpecialFolder.SendTo, list);
ShowSpecialFolder(Environment.SpecialFolder.StartMenu, list);

return list;
}

private void button1_Click_1(object sender, System.EventArgs e)
{
GetAllSpecialFolders(listBox1.Items);
}

This code begins with the last method, button1_Click_1, which will be called when the user clicks on a button. The button click method calls the GetAllSpecialFolders() method. GetAllSpecialFolders() has one call to ShowSpecialFolders for each of the special folders that the C# API tracks for you. Each call to ShowSpecialFolders creates one of the strings shown in Listing 1:

0	Desktop			C:/Documents and Settings/Charlie/Desktop

The ShowSpecialFolders method begins by getting the integer value of the member of the SpecialFolders enumeration that is passed in as a parameter:

 int i = (int)sp; 

This integer value appears at the beginning of the strings shown in Listing 1. For instance, it is the 0 before the word Desktop. This value is normally not important to developers, but I am showing it to you in case you are curious about the declaration of the SpecialFolders enumeration.In Microsoft's implementation of C#, we never see the source, so it is interesting to guess how it must be declared. For instance, in this case, the enumeration might look something like this:

enum SpecialFolder {Desktop=0, Programs=2, Personal=5, Favorites=6, Recent=8, etc);

The next line of my ShowSpecialFolders method begins with a call to String.Format. The String.Format() method has a peculiar, but useful, syntax I have only seen in C#. Each of the instances of code that appears in curly braces is replaced by one of the latter parameters passed to the method. For instance {0}, {1} and {2} get replaced with one of the parameters such as '/t' or sp.ToString() which is passed to String.Format. Note that '/t;' is the second parameter. It is the tab character, and will replace all instances of {0}. The variable i is the third parameter, and the value stored in that variable will replace each instance of {1}.

The code {2} is replaced by each instance of sp.ToString(). sp is a member of the SpecialFolder enumeration, and the ToString() method conveniently converts sp into a string representation of the enumeration member. That is, it converts sp into a string such as "Desktop", "Programs", "Personal", etc. In the String shown above, the value of i appears as 0, and sp.ToString() appears as Desktop. Again, programmers don't normally need to make a call to find out the string value of an enumeration, but it is interesting to know that you can do it if you so desire.

The last parameter, the one that goes into {3}, is the path, such as C:/Documents and Settings/Charlie/Desktop. I retrieved the path string by making the following call: Environment.GetFolderPath(sp). Note that I place three tabs in front of the path, to separate it from the rest of the code:

String S1 = String.Format("{1} {0} {2} {0}{0}{0} {3}", 't', i,
	sp.ToString(), Environment.GetFolderPath(sp));

I still had to manually edit some of the tabbing to make it come out as evenly as it appears in Listing 1.

Useful Methods

Listing 3 shows some other useful methods. Note that I use the GetEnvironmentVariable call to retrieve the Home Directory and in the call to GetEnvTempDir(). Since environment variables are mutable, these calls are probably less reliable than other calls. Also, they may be OS dependant. In particular, I have only tested them on XP. Note, however, the GetTempDir() call, which uses what should be a more reliable method of retreiving the temporary directory. In particular, it uses the Path object. The GetMyDocumentsDir() method is a wrapper around the Environment.SpecialFolder enumeration.

Listing 3: Routines for getting the users home directory, their My Documents directory, and the temp directory.

	public static String GetHomeDir()
{
return Environment.GetEnvironmentVariable("USERPROFILE");
}

public static String GetMyDocumentsDir()
{
return Environment.GetFolderPath(Environment.SpecialFolder.Personal);
}

public static String GetEnvTempDir()
{
return Environment.GetEnvironmentVariable("TEMP");
}

public static String GetTempDir()
{
return System.IO.Path.GetTempPath();
}

Summary

In this article you have learned a few simple tricks for getting system dependant information while using .NET. In particular, you learned about the Environment.SpecialFolder enumeration, and about the Environment.GetEnvironmentVariable method. The Environment class is part of the System namespace, so you should not have to add any special Using statements to your code other than the default Using System reference which should appear at the top of all C# files.

cartographer从入门到精通(一):cartographer介绍 Cartographer的架构图我们可以看到白色框出来的三个区域,分别是Input Sensor Data(数据输入模块)Local SLAM(局部SLAM模块)Global SLAM (background thread)(全局SLAM模块)下面我们分别介绍一下这几个模块。 阅读详情

相关推荐

JavaScript比较与逻辑运算符底层原理详解

JavaScript中的比较运算符(如==、===、>)和逻辑运算符(如&&、||)并非简单返回布尔值,而是基于类型转换规则(ToNumber、ToPrimitive、ToBoolean)执行抽象操作的确定性过程。理解其背后的标准协议——抽象相等比较、严格相等判断、关系运算数值化,以及逻辑运算的短路与原值返回机制,是避免隐式转换陷阱、写出可预测代码的关键。这些机制直接支撑着条件判断、默认值处理、安全访问等高频工程实践,广泛应用于表单校验、API响应处理、状态管理及UI渲染逻辑中。

weixin_32075843的博客 338

xml报错(dtd):The markup declarations contained or pointed to by the document type declaration must be ...

文件后缀为.xml里如下一行报错“The markup declarations contained or pointed to by the document type declaration must be well-formed.” <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybat...

weixin_34034670的博客 3969

PPPoe的抓包分析(详细)

PPPoe的报文结构 可以看出PPPoe的报文结构其实很简单,只不过是将PPPoe的报文塞到以太网的载荷中,而且它的头部字段也十分的简单,TLV就不说了,code字段表示了PPPoe不同的报文类型,比较常见的就是上面的五个报文了,PPPoe的报文类型其实还蛮多的。session ID主要的作用就是标识一段会话,因为使用PPPoe的最主要作用就是使得多台设备可以借助以太网多点接入多点访问的特点去和一台设备做上网认证请求,这样运营商一台认证设备就可以满足多个用户的认证请求,这和PPP相比起来好的不止一点。

qq_47529104的博客 7879

Guestinfo.hbm(1)The markup declarations contained or pointed to by the document type declaration mus...

今天启动ssh项目是居然报错了,还提示要联网启动,看了看错误信息发现,肯定是Hibernate映射文件的声明头出错了,仔细一下: hbm.xml中的dtd头直接是连接www.hibernate.org的,而不是sourceforge的,使用过HIbernate的同仁都应该知道,一般你下载Hibernate是从sourceforge上下载的,出错hbm.xml具体配置如下: &lt...

are27316的博客 1761

Mplus—验证性因素分析(Confirmatory Factor Analysis, CFA)

介绍一阶和二阶验证性因素分析概况及在Mplus中的操作方法。

m0_54401011的博客 1万+

一个基于ZYNQ、AXI接口的PL端卷积加速器,可由PS端调用(附Github源码)

一个基于ZYNQ,AXI接口的PL端卷积加速器,可由PS端调用开发板型号:Zynq-7000 SoC XC7Z305 FPGA开发平台:Vivado 2019.1;Github源码链接:https://github.com/CY0807/ZYNQ_PL_CONV_ACC。

跳跳骑士的博客 1316

XML内部DTD约束 Day24

<?xml version="1.0" encoding="UTF-8"?> <!-- 内部DTD --> <!-- XML:extensible markup language 可扩展标记语言 --> <!-- DTD约束:document type definition 文档类型定义 --> <!-- + 1~n * 0~...

weixin_30505043的博客 221

JLink版本不兼容?手把手教你解决APM32F003F6P6在Keil中烧写闪退和报错

本文详细解析了APM32F003F6P6在Keil中烧写闪退和报错的解决方案,重点介绍了JLink版本兼容性问题。通过实测不同版本组合,推荐使用JLink 7.20a或6.86b与Keil 5.25的黄金组合,并提供详细的降级驱动和工程配置步骤,帮助开发者高效解决烧写困境。

weixin_33694620的博客 419

tomcat7

严重: The markup declarations contained or pointed to by the document type declaration must be well-formed. at (-//Apache Software Foundation//DTD Struts Configuration 2.1//EN:1:2) org.xml.sax.SAXParse

fdgfdhgj的专栏 981

AUTOSAR进阶图解==>AUTOSAR_SWS_DefaultErrorTracer

AUTOSAR Default Error Tracer (DET)是AUTOSAR架构中的核心错误追踪模块,提供统一的错误报告机制。DET能够处理开发错误、运行时错误和瞬态故障三类问题,支持模块级和实例级的配置管理。模块架构上,DET通过Det_API接口与其他模块交互,可配置转发错误至诊断事件管理器(DEM)或调试日志追踪(DLT)。其配置结构包含全局参数和模块实例参数,允许灵活控制错误报告行为。DET在AUTOSAR 4.3.0版本中从DevelopmentErrorTracer扩展而来,增强了错误处

一名留德华的,康德的信徒的,专注于汽车电子领域的博客 914

《信息化项目文档模板十二——业务需求新增/变更审批确认表 》

系列文章目录 《信息化项目文档模板一——项目需求说明书》 《信息化项目文档模板二——项目启动会文档模板》 《信息化项目文档模板三——会议纪要模板》 《信息化项目文档模板四——系统项目蓝图设计模板》 《信息化项目文档模板五——系统详细设计模板》 《信息化项目文档模板六——系统详细设计模板》 《信息化项目文档模板七——系统开发计划模板》 《信息化项目文档模板八——系统功能测试模板》 《信息化项目文档模板九——系统压力测试模板》 《信息化项目文档模板十——系统推广上线计划模板》 《信息化项目文档模板十一——系统用

商务合作|问题讨论|交流学习 请联系作者微信,加微信请务必注明来意,博客主页有联系方式 1715

dom4j解析xml字符串时异常:org.dom4j.DocumentException: no protocol

dom4j解析xml字符串, 原采用: Document doc = new SAXReader().read(content); 报错: org.dom4j.DocumentException: no protocol 问题原因: 编码问题 解决方案: 1、检查工程编码、java文件编码、字符串编码,确保三者统一。 或 2、临时强制重新编码: D

路上的老薛 1万+

4、分布式发电系统中用于改善电能质量的有源、无源和混合滤波器

本文探讨了分布式发电系统中,尤其是光伏(PV)系统运行过程中引入的电能质量问题,并分析了有源滤波器、无源滤波器及混合滤波器在改善电能质量方面的应用。文章详细介绍了光伏系统的建模、最大功率点跟踪(MPPT)技术,以及谐波、电压波动等技术问题,同时对各类滤波器的拓扑结构和控制方法进行了系统性总结。通过仿真实例比较了不同滤波器在减少谐波方面的效果,为实际工程应用提供了参考依据。

transformer2023的博客 96

dom4j解析xml文件时忽略DOCTYPE标签

利用dom4j读取xml配置文件时,如果文件中出现DOCTYPE标签,可能会在read时读取异常: Document document = reader.read(file); 导致文件读取失败,如下: Exception in thread "main" org.dom4j.DocumentException: Error on line 1 of document http://t...

qq_42106106的博客 2691

vb 6.0并口开发操作实例

vb6并口开发,简体中文,试例内有inpout32.dll动态链接库

计算机控制技术及应用

《计算机控制技术及应用》通过总结作者的科研成果和吸收国内外的先进理论、方法和技术,以计算机控制系统的网络化、开放化、智能化和集成化发展趋势为主线索,主要介绍计算机控制系统的基本概念和计算机控制系统的典型形式,计算机控制系统的数学描述与基本分析方法,以及数字PID控制器、最少拍控制系统、达林算法、状态变量设计法等设计方法及其各种改进算法。重点突出计算机控制系统输入输出通道接口的设计方法和典型控制系统的设计案例与实现方法等。

XML(三):两种约束规则

DTD DTD : 对xml约束的规则 1,约束元素 1.1:元素出现的个数 1.2:元素出现的频率 1.3:元素出现的顺序 2,约束属性 2.1,什么属性可以出现必须出现 2.2,属性的值 可能是什么 | 2.3,能否文本 就是一套关于元素、属性以及其他杂项在xml文档中使用规则的声明。 DTD:可以限定: 标签,文本域,属性 DTD:Document Type Definition 1.定义...

qq_41170640的博客 845

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

xml解析请求DTD错误的解决办法(断网服务器下):org.xml.sax.SAXParseExceptionpublicId

最近我的web程序部署到一台新的服务器(这是台无法访问网络的服务器),启动时总是报解析XML错误,说某个jar包里的XML文件不可用的错误:xml] is invalid 原来这是因为解析XML文件的时候校验dtd失效,因为我的XML里对xsd文件引用都是http路径的网络资源文件,而在断网情况下http请求失败,所以导致无法下载xsd文件而无法解析xml 经过一番百度、google,终于

lizhikang2009的博客 1万+

Java杂项

欢迎和大家交流技术相关问题: 邮箱: jiangxinnju@163.com 博客园地址: http://www.cnblogs.com/jiangxinnju GitHub地址: https://github.com/jiangxincode 知乎地址: https://www.zhihu.com/people/jiangxinnju JDK JDK(Java Development Kit)是...

weixin_30340775的博客 220

各种 html DOCTYPE Declarations

HTML 5   HTML 4.01 Strict This DTD contains all HTML elements and attributes, but does NOT INCLUDE presentational or deprecated elements (like font). Framesets are not allowed.   HTML 4.01

影子睿变 557
上一篇: BDNradio: Chat room log of live chat with Danny Thorpe on Delphi 2005 - by John Kaster
下一篇: Namespaces in Delphi 2005 by Marc Rohloff
zqc-tutorial
博客等级 码龄24年 8粉丝 39原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值