Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
SQL Server

Getting and Setting the Current Directory:

Author: DevASP
Download Source Code :

This article discusses the methods available in the Win32 System Services APIs for manipulating directories, such as Set the current directory or find out the current directory.

It is easy to get and set an application's current directory using the Get CurrentDirectory and SetCurrentDirectory functions of Win32 System Services.The sample code attached with this article starts by retrieving the current directory and printing it to a MessageBox. It then requests a new directory name from the user, and sets the current directory appropriately. It retrieves the current directory again to show that it has been set successfully. Note that the directory change applies only to the application's perspective—the user's current directory in the command shell will not change.



                                 Retrieves the current directory name



DWORD GetCurrentDirectory(DWORD bufferSize ,LPTSTR buffer); 


bufferSize - Size of the buffer.

buffer - Buffer to hold the current directory string. 

Returns the number of characters in the buffer or 0 on error.



                               Sets the current directory.



BOOL SetCurrentDirectory(LPTSTR newDir); 


newDir - String containing the new directory path

Returns TRUE on success.


If either of these functions detects an error, GetLastError contains the error value.The code snip below will show u a message box which will display the current directry to you.



char buffer[MAX_PATH];

DWORD len;

BOOL success;

len = GetCurrentDirectory(MAX_PATH, buffer);

if (len == 0)


      CString strMessage;

      strMessage.Format("Cant get Current directory Reason:%s",GetLastError());





        CString strMessage;

        strMessage.Format("the current directory is:%s",buffer);




And the code code snip below will change the current directory to the “C:\\Document and Settings” .



char s[MAX_PATH]="C:\\Documents and Settings";

BOOL success;

// change directory

success = SetCurrentDirectory(s);

if (!success)

     MessageBox("Cant Set Current error","error");


   MessageBox("Directory changed successfully");


To test the code you can click on the “Get Current Directory” Button this will show you the current directory and then press the change directory . this will change the current directory.By clicking again on “Get Current Directory” you can see the effect of change directory.

Add Article Comment:
Name :
Email Address :
Comments :
<< Creating and Removing Directories using Win32 System Services API

Disclaimer - Privacy
© 2002-2017