Directory.SetCurrentDirectory(String) メソッド

定義

アプリケーションの現在の作業ディレクトリを指定したディレクトリに設定します。

public static void SetCurrentDirectory (string path);

パラメーター

path
String

現在の作業ディレクトリが設定されるパス。

例外

I/O エラーが発生しました。

.NET Framework バージョンと .NET Core バージョンが 2.1 より前の場合: path は長さ 0 の文字列、空白のみを含む、または無効な文字が 1 つ以上含まれています。 GetInvalidPathChars() メソッドを使用して、正しくない文字に対するクエリを実行できます。

pathnullです。

指定したパス、ファイル名、またはその両方がシステム定義の最大長を超えています。

呼び出し側に、アンマネージ コードへのアクセスに必要なアクセス許可がありません。

指定したパスが見つかりませんでした。

指定されたディレクトリが見つかりませんでした。

次の例は、現在のディレクトリを設定し、ディレクトリ ルートを表示する方法を示しています。

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

注釈

アプリケーションが終了すると、作業ディレクトリは元の場所 (プロセスが開始されたディレクトリ) に復元されます。

パラメーターは path 、相対パス情報または絶対パス情報を指定できます。 相対パス情報は、現在の作業ディレクトリに対する相対パスとして解釈されます。 現在の作業ディレクトリを取得するには、「」を参照してください GetCurrentDirectory

ディレクトリを設定する前に、 path パラメーターの末尾から末尾のスペースが削除されます。

パラメーターの大文字と小文字の path 区別は、コードが実行されているファイル システムの大文字と小文字が区別されます。 たとえば、NTFS (既定の Windows ファイル システム) では大文字と小文字が区別されず、Linux ファイル システムでは大文字と小文字が区別されます。

リムーバブル メディアを含むドライブ (USB フラッシュ ドライブの場合は "E:" など) にディレクトリを設定する場合は、 プロパティを使用 IsReady してドライブの準備ができているかどうかを判断できます。

適用対象

製品 バージョン
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 1.3, 1.4, 1.6, 2.0, 2.1
UWP 10.0

こちらもご覧ください