Directory.SetCurrentDirectory(String) Método

Definición

Establece el directorio de trabajo actual de la aplicación en el directorio especificado.

public:
 static void SetCurrentDirectory(System::String ^ path);
public static void SetCurrentDirectory (string path);
static member SetCurrentDirectory : string -> unit
Public Shared Sub SetCurrentDirectory (path As String)

Parámetros

path
String

Ruta de acceso en la que se establece el directorio de trabajo actual.

Excepciones

Error de E/S.

Versiones de .NET Framework y .NET Core anteriores a 2.1: path es una cadena de longitud cero, solo contiene espacios en blanco o contiene uno o varios caracteres no válidos. Puede consultar los caracteres no válidos con el método GetInvalidPathChars().

path es null.

La ruta de acceso especificada, el nombre de archivo o ambos superan la longitud máxima definida por el sistema.

El llamador no dispone del permiso requerido para obtener acceso al código no administrado.

No se encontró la ruta de acceso especificada.

No se encuentra el directorio especificado.

Ejemplos

En el ejemplo siguiente se muestra cómo establecer el directorio actual y mostrar la raíz del directorio.

// This sample shows how to set the current directory and how to determine
// the root directory.
using namespace System;
using namespace System::IO;
int main()
{
   
   // Create string for a directory. This value should be an existing directory
   // or the sample will throw a DirectoryNotFoundException.
   String^ dir = "C:\\test";
   try
   {
      
      //Set the current directory.
      Directory::SetCurrentDirectory( dir );
   }
   catch ( DirectoryNotFoundException^ e ) 
   {
      Console::WriteLine( "The specified directory does not exist. {0}", e );
   }

   
   // Print to console the results.
   Console::WriteLine( "Root directory: {0}", Directory::GetDirectoryRoot( dir ) );
   Console::WriteLine( "Current directory: {0}", Directory::GetCurrentDirectory() );
}

// The output of this sample depends on what value you assign to the variable dir.
// If the directory c:\test exists, the output for this sample is:
// Root directory: C:\
// Current directory: C:\test
// This sample shows how to set the current directory and how to determine
// the root directory.
using System;
using System.IO;

namespace IOSamples
{
  public class DirectoryRoot
  {
    public static void Main()
    {
    // Create string for a directory. This value should be an existing directory
    // or the sample will throw a DirectoryNotFoundException.
      string dir = @"C:\test";		
      try
      {
          //Set the current directory.
          Directory.SetCurrentDirectory(dir);
      }
      catch (DirectoryNotFoundException e)
      {
          Console.WriteLine("The specified directory does not exist. {0}", e);
      }
    // Print to console the results.
      Console.WriteLine("Root directory: {0}", Directory.GetDirectoryRoot(dir));
      Console.WriteLine("Current directory: {0}", Directory.GetCurrentDirectory());
    }
  }
}
// The output of this sample depends on what value you assign to the variable dir.
// If the directory c:\test exists, the output for this sample is:
// Root directory: C:\
// Current directory: C:\test
// This sample shows how to set the current directory and how to determine
// the root directory.
open System.IO

// Create string for a directory. This value should be an existing directory
// or the sample will throw a DirectoryNotFoundException.
let dir = @"C:\test"
try
    //Set the current directory.
    Directory.SetCurrentDirectory dir
with :? DirectoryNotFoundException as e ->
    printfn $"The specified directory does not exist. {e}"
    
// Print to console the results.
printfn $"Root directory: {Directory.GetDirectoryRoot dir}"
printfn $"Current directory: {Directory.GetCurrentDirectory()}"
// The output of this sample depends on what value you assign to the variable dir.
// If the directory c:\test exists, the output for this sample is:
// Root directory: C:\
// Current directory: C:\test
' This sample shows how to set the current directory and how to determine
' the root directory.
Imports System.IO

Public Class DirectoryRoot
   
   Public Shared Sub Main()
      ' Create string for a directory. This value should be an existing directory
      ' or the sample will throw a DirectoryNotFoundException.
      Dim dir As String = "C:\test"
      Try
         'Set the current directory.
         Directory.SetCurrentDirectory(dir)
      Catch e As DirectoryNotFoundException
         Console.WriteLine("The specified directory does not exist. {0}", e)
      End Try
      ' Print to console the results.
      Console.WriteLine("Root directory: {0}", Directory.GetDirectoryRoot(dir))
      Console.WriteLine("Current directory: {0}", Directory.GetCurrentDirectory())
   End Sub
End Class
' The output of this sample depends on what value you assign to the variable dir.
' If the directory c:\test exists, the output for this sample is:
' Root directory: C:\
' Current directory: C:\test

Comentarios

Cuando finaliza la aplicación, el directorio de trabajo se restaura en su ubicación original (el directorio donde se inició el proceso).

El path parámetro puede especificar información de ruta de acceso relativa o absoluta. La información de ruta de acceso relativa se interpreta como relativa al directorio de trabajo actual. Para obtener el directorio de trabajo actual, vea GetCurrentDirectory.

Los espacios finales se quitan del final del path parámetro antes de establecer el directorio.

La distinción entre mayúsculas y minúsculas del path parámetro corresponde al del sistema de archivos en el que se ejecuta el código. Por ejemplo, no distingue mayúsculas de minúsculas en NTFS (el sistema de archivos de Windows predeterminado) y distingue mayúsculas de minúsculas en sistemas de archivos Linux.

Si va a establecer el directorio en una unidad con medios extraíbles (por ejemplo, "E:" para una unidad flash USB), puede determinar si la unidad está lista mediante la IsReady propiedad .

Se aplica a

Consulte también