DirectoryInfo(String) 构造函数
定义
重要
一些信息与预发行产品相关,相应产品在发行之前可能会进行重大修改。 对于此处提供的信息,Microsoft 不作任何明示或暗示的担保。
在指定路径上初始化类的新实例 DirectoryInfo 。
public:
DirectoryInfo(System::String ^ path);
public DirectoryInfo(string path);
new System.IO.DirectoryInfo : string -> System.IO.DirectoryInfo
Public Sub New (path As String)
参数
- path
- String
一个字符串,指定要在其中创建 DirectoryInfo路径的字符串。
例外
path 是 null。
调用方没有所需的权限。
.NET Framework 和低于 2.1 的 .NET Core 版本:path 包含无效字符,例如“、<、> 或 |。
指定的路径、文件名或两者都超过了系统定义的最大长度。
示例
以下示例使用此构造函数创建指定的目录和子目录,并演示无法删除包含子目录的目录。
using System;
using System.IO;
class Test
{
public static void Main()
{
// Specify the directories you want to manipulate.
DirectoryInfo di1 = new DirectoryInfo(@"c:\MyDir");
DirectoryInfo di2 = new DirectoryInfo(@"c:\MyDir\temp");
try
{
// Create the directories.
di1.Create();
di2.Create();
// This operation will not be allowed because there are subdirectories.
Console.WriteLine("I am about to attempt to delete {0}.", di1.Name);
di1.Delete();
Console.WriteLine("The Delete operation was successful, which was unexpected.");
}
catch (Exception)
{
Console.WriteLine("The Delete operation failed as expected.");
}
finally {}
}
}
open System.IO
// Specify the directories you want to manipulate.
let di1 = DirectoryInfo @"c:\MyDir"
let di2 = DirectoryInfo @"c:\MyDir\temp"
try
// Create the directories.
di1.Create()
di2.Create()
// This operation will not be allowed because there are subdirectories.
printfn $"I am about to attempt to delete {di1.Name}."
di1.Delete()
printfn "The Delete operation was successful, which was unexpected."
with _ ->
printfn "The Delete operation failed as expected."
Imports System.IO
Public Class Test
Public Shared Sub Main()
' Specify the directories you want to manipulate.
Dim di1 As DirectoryInfo = New DirectoryInfo("c:\MyDir")
Dim di2 As DirectoryInfo = New DirectoryInfo("c:\MyDir\temp")
Try
' Create the directories.
di1.Create()
di2.Create()
' This operation will not be allowed because there are subdirectories.
Console.WriteLine("I am about to attempt to delete {0}.", di1.Name)
di1.Delete()
Console.WriteLine("The Delete operation was successful, which was unexpected.")
Catch e As Exception
Console.WriteLine("The Delete operation failed as expected.")
End Try
End Sub
End Class
注解
此构造函数不检查目录是否存在。 此构造函数是用于在后续操作中访问磁盘的字符串的占位符。
参数 path 可以是文件名,包括通用命名约定(UNC)共享上的文件。
Caution
使用特定区域性设置编译一组字符并检索具有不同区域性设置的相同字符时,这些字符可能无法解释,并可能导致引发异常。
有关常见 I/O 任务的列表,请参阅 常见 I/O 任务。