DirectoryInfo类用于复制、移动、重命名、创建和删除目录等典型操作。用Directory类的Exists 方法可以简单快速的判
断文件夹是否存在,参数是文件的路径。返回值是Boolean型。返回True说明文件夹存在,返回False说明文件夹不存
在。
例如,判断E盘下是否存在名为soft的文件夹。代码如下所示:
Directory.Exists("E:\soft "); |
创建文件夹: |
通过DirectoryInfo类的Create 方法可以方便地创建文件夹。参数是将要创建的文件夹路径。返回值是一个由参数指
定的DirectoryInfo对象。
本例演示了通过Directory类的Create 方法来创建文件夹。
程序代码如下:
代码
protectedvoid
Button1_Click(object
sender,EventArgse)
{
stringName
=
TextBox1.Text.ToString();
string Path
=Server.MapPath(".")+
"\"+
Name;
DirectoryInfo di =new
DirectoryInfo(Path);
if
(di.Exists)
{
Page.RegisterStartupScript("","<script>alert('该文件夹已经存在')</script>");
}
else
{
di.Create();
Page.RegisterStartupScript("","<script>alert('创建文件夹成功')</script>");
}
}
移动文件夹: |
通过DirectoryInfo类的MoeTo方法可以对文件夹方便地进行移动。在移动的过程中会将目录及其内容一起移动,
第一个参数是要移动的文件或目录的路径,第二个参数是文件夹的新路径。
本例演示了通过DirectoryInfo类的MoveTo 方法移动文件夹
程序代码如下:
代码
protected
void Button1_Click(object
sender, EventArgse)
{
DirectoryInfo di =new
DirectoryInfo(TextBox1.Text.ToString());
DirectoryInfo di2 =new
DirectoryInfo(TextBox2.Text.ToString());
if (!di.Exists)
{
//源文件不存在
return;
}
if(di2.Exists)
{
//目标文件夹已存在
return;
}
di.MoveTo(TextBox2.Text.ToString());
}
删除文件夹: |
DirectoryInfo类的Delete方法可以用来删除文件夹。参数是要删除的文件夹的路径。
本例演示了通过DirectoryInfo类的Delete方法删除文件夹。
程序代码如下:
代码
try
{
DirectoryInfo di =new
DirectoryInfo(TextBox1.Text.ToString());
if
(di.Exists)
{
di.Delete();
//删除成功
}
else
{
//文件夹不存在
return;
}
}
catch(Exceptionex)
{
returnex.ToString();
}
|
|
|