`
netatomy
  • 浏览: 46843 次
  • 性别: Icon_minigender_1
  • 来自: 南京
社区版块
存档分类
最新评论

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

 
阅读更多
.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 -->Rating is 3.5 - 4.5 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.

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.

分享到:
评论

相关推荐

    Essential LINQ

    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

    "Calvert"是一种著名的字体,源自1978年,这可能是压缩包内文件名称的由来。在IT行业中,字体扮演着至关重要的角色,它不仅关乎文本的可读性,还影响着整体设计的视觉效果。让我们深入探讨一下"Calvert"字体以及字体...

    Delphi编程技巧.rar

    DELPHI AND THE INTERNET by Charlie Calvert [1] DELPHI AND THE INTERNET by Charlie Calvert [2] Delphi之快速设计(程序设计篇) Delphi之快速设计(界面设计篇) 在DELPHI2.0/3.0中直接操作端口 开 发AS/...

    Addison Wesley Essential LINQ Mar 2009 pdf

    《Addison Wesley Essential LINQ Mar 2009》是一本深入探讨了LINQ(Language Integrated Query)技术的专业书籍,由Charlie Calvert和Dinesh Kulkarni共同撰写。这本书旨在为读者提供一个全面而深入的理解LINQ的...

    Essential+LINQ

    《Essential LINQ》这本书由Charlie Calvert和Dinesh Kulkarni共同撰写,是一部深入探讨LINQ(Language Integrated Query)技术的权威著作。LINQ是微软在.NET Framework 3.5中引入的一项重要技术,它使得在C#和其他...

    JsObjects:一些有关基本对象语法JavaScript程序

    的对象查理·卡尔弗特(Charlie Calvert) 该存储库包含Charlie Calvert为其班级和Elvenware提供的示例代码。 在其中,您会找到各种示例JavaScript,HTML,CSS,Node,Bash脚本和Python项目。 要正确安装JsObjects的...

    C++Builder应用开发大全随书光盘代码.zip

    卡尔弗特]Charlie Calvert[等]著 出版社: 清华大学出版社 ISBN: 9787302035985 出版时间: 1999-06 印刷时间: 1999-06 装帧: 平装 开本: 16开 页数: 1115页 无意中找到随书光盘,特将代码部分打包分享。

    Elvenware Source Code-开源

    Charlie Calvert是一位知名的编程专家,他的书籍、讲座和文章在IT行业中广受赞誉。他所创建的"Elvenware Source Code"项目,不仅是一个个人作品的集合,更是一个开放源码的宝库,为开发者们提供了丰富的学习和实践...

    《Linq实战》

    考虑到本书是由Charlie Calvert和Dinesh Kulkarni所著,并且出版社为Pearson Education, Inc.,这暗示了该书具有一定的权威性。出版社提供的信息中,还包含了版权信息、出版社的联系方式、以及有关批量购买和特殊...

    yoshimi:一个复杂的软合成器,最初是由Alan Calvert在2009年从ZynAddSubFX V2.4.0派生的,并且仍在持续开发中-这也反映在http:sourceforge.netprojectsyoshimi上:当前新闻位于http://sourceforge.netpyoshiminews:我们的电子邮件讨论列表是:http://www.freelists.orglistyoshimi,这是我们的网站

    Yoshimi,这款由Alan Calvert于2009年基于ZynAddSubFX V2.4.0创建并持续发展的软合成器,已经成为音乐制作领域中的一个重要工具。它不仅继承了ZynAddSubFX的丰富功能,还不断进行创新与改进,为音乐制作者提供了更多...

    TCP.IP.Sockets.in.Java.2nd.Edition

    Calvert与Michael J. Donahoo共同编写,并于2008年出版。该书是Morgan Kaufmann出版社“实用指南系列”之一,旨在为读者提供全面、实用的网络编程知识。 #### 关键知识点解析 **1. 网络编程基础** - **协议栈**...

    TCPIP.Sockets.in.Java.Second.Edition

    - **Java Socket API**:深入讲解了Java中的Socket API,包括`java.net.Socket`与`java.net.ServerSocket`类的使用方法。 - **非阻塞Socket**:介绍如何使用NIO来实现非阻塞式的Socket编程,提高程序效率。 - **多...

    TCPIP Sockets in C#

    Calvert。 4. 书籍系列和相关主题: 从提供的部分内容中我们可以看到,该系列还包括了其他有关Java和网络编程的书籍,例如《TCP/IP Sockets in Java》和《JDBC: Practical Guide for Java Programmers》。这表明...

    printf:西蒙·孙(Simon Sun)和乍得·卡尔弗特(Chad Calvert)printf项目

    本文将深入探讨由西蒙·孙(Simon Sun)和乍得·卡尔弗特(Chad Calvert)合作的`printf`项目,分析其核心概念、工作原理以及在实际编程中的应用。 `printf`函数源自C语言的标准输入输出库(stdio.h),它的名字...

    C++ Builder Unleashed(英文版).pdf

    《C++ Builder Unleashed》是Charlie Calvert所著的一本经典教材,该书详细介绍了如何使用C++ Builder进行软件开发。本书内容全面且深入,不仅适合初学者入门,也适合有经验的开发者进一步提升技能。下面将基于提供...

    Borland_C++_Builder_Unleashed.[EN]

    《Borland C++ Builder Unleashed》一书由Charlie Calvert编写,是关于Borland C++ Builder软件的深入指南。此书旨在为开发者提供全面的C++ Builder使用技巧和高级编程技术,覆盖了从基础操作到复杂数据库管理、组件...

Global site tag (gtag.js) - Google Analytics