Directory.SetCurrentDirectory(String) Método

Definição

Define o diretório de trabalho atual da aplicação para o diretório 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

O caminho para onde está definido o diretório de trabalho atual.

Exceções

Ocorreu um erro de I/O.

.NET Framework e .NET Core versões anteriores à 2.1: path é uma cadeia de comprimento zero, contém apenas espaço em branco ou contém um ou mais caracteres inválidos. Podes consultar caracteres inválidos com o GetInvalidPathChars() método.

path é null.

O caminho especificado, nome do ficheiro ou ambos excedem o comprimento máximo definido pelo sistema.

O interlocutor não tem a permissão necessária para aceder a código não gerido.

O caminho especificado não foi encontrado.

O diretório especificado não foi encontrado.

Exemplos

O exemplo seguinte ilustra como definir o diretório atual e mostrar a raiz do diretório.

// 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

Observações

Quando a aplicação termina, o diretório de trabalho é restaurado para a sua localização original (o diretório onde o processo foi iniciado).

O path parâmetro pode especificar informação relativa ou absoluta do caminho. A informação relativa do caminho é interpretada como relativa ao diretório de trabalho atual. Para obter o diretório de trabalho atual, veja GetCurrentDirectory.

Os espaços finais são removidos do final do path parâmetro antes de definir o diretório.

A sensibilidade a maiúsculas e minúsculas do path parâmetro corresponde à do sistema de ficheiros onde o código está a correr. Por exemplo, é insensível a maiúsculas minúsculas no NTFS (o sistema de ficheiros padrão do Windows) e sensível a maiúsculas minúsculas em sistemas de ficheiros Linux.

Se estiver a definir o diretório para um disco com suporte removível (por exemplo, "E:" para uma pen USB), pode determinar se o disco está pronto usando esta IsReady propriedade.

Aplica-se a

Ver também