Directory.SetCurrentDirectory(String) Метод
Определение
Важно!
Некоторые сведения относятся к предварительной версии продукта, в которую до выпуска могут быть внесены существенные изменения. Майкрософт не предоставляет никаких гарантий, явных или подразумеваемых, относительно приведенных здесь сведений.
Задает текущий рабочий каталог приложения указанному каталогу.
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)
Параметры
- path
- String
Путь к которому задан текущий рабочий каталог.
Исключения
Произошла ошибка ввода-вывода.
Версии .NET Framework и .NET Core старше 2.1: path представляет собой строку нулевой длины, содержит только пробелы или содержит один или несколько недопустимых символов. Вы можете запросить недопустимые символы с GetInvalidPathChars() помощью метода.
path равно null.
Указанный путь, имя файла или оба превышают определенную системой максимальную длину.
Вызывающий объект не имеет требуемого разрешения на доступ к неуправляемом коду.
Указанный путь не найден.
Указанный каталог не найден.
Примеры
В следующем примере показано, как задать текущий каталог и отобразить корневой каталог.
// 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
Комментарии
После завершения работы приложения рабочий каталог восстанавливается в исходном расположении (каталог, в котором был запущен процесс).
Параметр path может указывать относительные или абсолютные сведения о пути. Относительные сведения о пути интерпретируются как относительные к текущему рабочему каталогу. Чтобы получить текущий рабочий каталог, см. GetCurrentDirectory.
Конечные пробелы удаляются из конца path параметра перед установкой каталога.
Конфиденциальность регистра path параметра соответствует файловой системе, в которой выполняется код. Например, это не учитывает регистр в NTFS (файловая система Windows по умолчанию) и учитывает регистр в файловых системах Linux.
Если вы устанавливаете каталог на диск с съемным носителем (например, "E:" для USB-флэш-накопителя), можно определить, готов ли диск с помощью IsReady свойства.