- 浏览: 43884 次
- 性别:
- 来自: 南京
最新评论
.NET tip: Getting the Users Home, Temp or My Documents Directory by Charlie Calvert
<!-- Vignette StoryServer 4 Wed Dec 15 19:46:21 2004 -->Rating: <!-- Vignette StoryServer 4 Wed Dec 15 03:05:44 2004 --> Ratings:67 Rate it
<!-- end of rating summary component-->
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.
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.
相关推荐
Charlie Calvert, Community Program Manager for the Microsoft C# team, currently focuses his technical energies on LINQ. He has periodically worked with LINQ Chief Architect Anders Hejlsberg both ...
CALVERT
For years, college courses in computer networking were taught with little or no hands-on experience. For various reasons, including some good ones, instructors approached the principles of computer ...
By applying the lessons from this book to your own code, you will find many ways to polish and improve the work that you produce.' -Charlie Calvert, Community Program Manager, Visual C#, Microsoft In...
DELPHI AND THE INTERNET by Charlie Calvert [1] DELPHI AND THE INTERNET by Charlie Calvert [2] Delphi之快速设计(程序设计篇) Delphi之快速设计(界面设计篇) 在DELPHI2.0/3.0中直接操作端口 开 发AS/...
的对象查理·卡尔弗特(Charlie Calvert) 该存储库包含Charlie Calvert为其班级和Elvenware提供的示例代码。 在其中,您会找到各种示例JavaScript,HTML,CSS,Node,Bash脚本和Python项目。 要正确安装JsObjects的...
卡尔弗特]Charlie Calvert[等]著 出版社: 清华大学出版社 ISBN: 9787302035985 出版时间: 1999-06 印刷时间: 1999-06 装帧: 平装 开本: 16开 页数: 1115页 无意中找到随书光盘,特将代码部分打包分享。
Charlie Calvert的一部经典之作,是学习C++Builder的好教材.根据网络教程本人制作的pdf版,便于学习和参考.
yoshimi:一个复杂的软合成器,最初是由Alan Calvert在2009年从ZynAddSubFX V2.4.0派生的,并且仍在持续开发中-这也反映在http:sourceforge.netprojectsyoshimi上:当前新闻位于...我们的电子邮件讨论列表是:...
该站点旨在成为 Charlie Calvert 的书籍、讲座、文章和编程项目的代码库。 我计划将我所有的代码作为开源发布。
The Morgan Kaufmann practical guides series Edition 2nd ed. Year 2009 Language eng ISBN 9780123745408 (pbk.) · 0123745403 (pbk.) LC Control No. 2009280295 Bibliography Includes bibliographical ...
<<<<<<< HEAD printf 印刷品 63b59bb49ddcd3043b9f10b106652e8474749c35
nexmo API 的 nodejs 包装器安装$ meteor add calvert:simple-nexmo初始化安装后,您可以通过以下方式初始化包: var nexmo = new Nexmo ( { apiKey : 'YOUR_API_KEY' , apiSecret : 'YOUR_API_SECRET' , baseUrl : ...
电路JS1介绍CircuitJS1是在浏览器中运行的电子电路模拟器。 它最初是由Paul Falstad作为Java Applet编写的。... 雅各布·卡尔弗特(Jacob Calvert)担任T型触发器; Ben Hayden的范围光谱; Thomas Reitinger,Krystia
[美]卡尔弗特(Calvert,K.L.)
Michael J.Donahoo and Kenneth L.Calvert 编著详细 条理清晰
Google Maps简易标记 一个简单的工具,用于生成带有标记的嵌入式Google地图。 MIT许可证(MIT) ... 特此免费授予获得此软件和相关文档文件(“软件”)副本的任何人无限制地处理软件的权利,包括但不限于使用,复制,...
" "[5] Kenneth L.Calvert.Java TCP/IP Socket编程[M].北京:机械工业 " "出版社,2009.1 " "指导教师(签名): "教研室主任(签名): " 企业网组建与设计 x 摘要:企业网络的主干所承担的信息流量很大,企业网络...
Linux的软件合成器,最初由Alan Calvert于2009年从ZynAddSubFX(版权所有2002-2009 Nasca Octavian Paul)创建。 最初,吉见提供了相同的合成器功能。 在对Jack和Alsa midi /音频性能进行了早期改进之后,现在添加了...
准确预测文丘里洗涤器的压力损失并加以合理利用,是设备优化设计...推导出了1个简单、准确的文丘里洗涤器压力损失模型该模型的理论预测值和实验值一致,并在实验基础上将该模型和修正的Calvert模型及Yung模型进行了对比。