System.IO Namespace
Provides types that allow reading and writing files and data streams, and types that represent and operate on a file system.
Directory Class
Exposes static
members for creating, moving, and enumerating through directories and subdirectories.
Members
static void SetCurrentDirectory(string path)
Sets the current working directory to the specified path.
Parameters
Name | Type | Description |
---|---|---|
path |
string | The path to which the current directory is set. This path must be a fully qualified directory name. |
Exceptions
Type | Description |
---|---|
ArgumentNullException |
path is null . |
ArgumentException |
path is empty, contains only white space, or contains one or more invalid characters. |
DirectoryNotFoundException |
The specified path is invalid. For example, it might be on an unmapped drive. |
IOException |
An I/O error occurred while opening the directory. |
UnauthorizedAccessException |
The caller does not have the required permission. |
Remarks
The current working directory is the directory from which an application is started. For example, if you start an application from the command line, the current working directory is the directory that is current when you enter the command.
If the application is started from a non-empty path, the current working directory is the directory that contains the executable file.
Use the Directory.GetCurrentDirectory
method to get the current working directory.
Example
The following code example demonstrates how to use the SetCurrentDirectory method.
using System;
using System.IO;
public class Example
{
public static void Main()
{
// Get the current directory.
string oldDirectory = Directory.GetCurrentDirectory();
Console.WriteLine("The current directory is: {0}", oldDirectory);
// Set the new directory.
// NOTE: Replace "C:\Temp" with a valid directory path on your system.
string newDirectory = @"C:\Temp";
try
{
Directory.SetCurrentDirectory(newDirectory);
Console.WriteLine("Successfully changed directory to: {0}", Directory.GetCurrentDirectory());
}
catch (DirectoryNotFoundException)
{
Console.WriteLine("Directory not found: {0}", newDirectory);
}
catch (UnauthorizedAccessException)
{
Console.WriteLine("Access denied to directory: {0}", newDirectory);
}
finally
{
// Restore the original directory.
Directory.SetCurrentDirectory(oldDirectory);
Console.WriteLine("Restored original directory: {0}", Directory.GetCurrentDirectory());
}
}
}