Directory.GetCurrentDirectory 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
取得應用程式的目前工作目錄。
public:
static System::String ^ GetCurrentDirectory();
public static string GetCurrentDirectory ();
static member GetCurrentDirectory : unit -> string
Public Shared Function GetCurrentDirectory () As String
傳回
字串,其中包含目前工作目錄的絕對路徑,且結尾不會以反斜杠 (\) 結尾。
例外狀況
呼叫端沒有必要的權限。
範例
下列範例示範如何使用 GetCurrentDirectory
方法。
using namespace System;
using namespace System::IO;
int main()
{
try
{
// Get the current directory.
String^ path = Directory::GetCurrentDirectory();
String^ target = "c:\\temp";
Console::WriteLine( "The current directory is {0}", path );
if ( !Directory::Exists( target ) )
{
Directory::CreateDirectory( target );
}
// Change the current directory.
Environment::CurrentDirectory = target;
if ( path->Equals( Directory::GetCurrentDirectory() ) )
{
Console::WriteLine( "You are in the temp directory." );
}
else
{
Console::WriteLine( "You are not in the temp directory." );
}
}
catch ( Exception^ e )
{
Console::WriteLine( "The process failed: {0}", e );
}
}
using System;
using System.IO;
class Test
{
public static void Main()
{
try
{
// Get the current directory.
string path = Directory.GetCurrentDirectory();
string target = @"c:\temp";
Console.WriteLine("The current directory is {0}", path);
if (!Directory.Exists(target))
{
Directory.CreateDirectory(target);
}
// Change the current directory.
Environment.CurrentDirectory = (target);
if (path.Equals(Directory.GetCurrentDirectory()))
{
Console.WriteLine("You are in the temp directory.");
}
else
{
Console.WriteLine("You are not in the temp directory.");
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
open System
open System.IO
try
// Get the current directory.
let path = Directory.GetCurrentDirectory()
let target = @"c:\temp"
printfn $"The current directory is {path}"
if not (Directory.Exists target) then
Directory.CreateDirectory target |> ignore
// Change the current directory.
Environment.CurrentDirectory <- target
if path.Equals(Directory.GetCurrentDirectory()) then
printfn "You are in the temp directory."
else
printfn "You are not in the temp directory."
with e ->
printfn $"The process failed: {e}"
Imports System.IO
Public Class Test
Public Shared Sub Main()
Try
' Get the current directory.
Dim path As String = Directory.GetCurrentDirectory()
Dim target As String = "c:\temp"
Console.WriteLine("The current directory is {0}", path)
If Directory.Exists(target) = False Then
Directory.CreateDirectory(target)
End If
' Change the current directory.
Environment.CurrentDirectory = (target)
If path.Equals(Directory.GetCurrentDirectory()) Then
Console.WriteLine("You are in the temp directory.")
Else
Console.WriteLine("You are not in the temp directory.")
End If
Catch e As Exception
Console.WriteLine("The process failed: {0}", e.ToString())
End Try
End Sub
End Class
備註
目前的目錄與原始目錄不同,這是程序啟動的來源目錄。
如需一般 I/O 工作的清單,請參閱 一般 I/O 工作。