本文采用C#語(yǔ)言實(shí)現(xiàn)創(chuàng)建,刪除和移動(dòng)文件夾以及文件夾列表的功能,代碼如下:
使用Directory類(lèi)和DirectoryInfo類(lèi)
一、創(chuàng)建文件夾
try
...{
if (System.IO.Directory.Exists(DirectoryTextBox.Text))
...{
MsgLabel.Text = "該文件夾已經(jīng)存在";
return;
}
else
...{
System.IO.DirectoryInfo dirinfo = System.IO.Directory.CreateDirectory(DirectoryTextBox.Text);
MsgLabel.Text = "成功創(chuàng)建該文件夾!創(chuàng)建時(shí)間為:" + System.IO.Directory.GetCreationTime(DirectoryTextBox.Text);
}
}
catch (Exception ee)
...{
MsgLabel.Text = "處理失??! 失敗的原因是:" + ee.ToString();
}
二、刪除文件夾
try
...{
if (!Directory.Exists(DirectoryTextBox.Text))
...{
MsgLabel.Text = "該文件不存在";
}
else
...{
Directory.Delete(DirectoryTextBox.Text);
MsgLabel.Text = "刪除文件成功!";
}
}
catch (Exception ee)
...{
MsgLabel.Text = "操作失?。?失敗的原因是:" + ee.ToString();
}
三、移動(dòng)文件夾
源文件夾和目標(biāo)文件夾要求存在于同一個(gè)硬盤(pán)分區(qū)中否則會(huì)操作失敗(操作失?。?失敗原因:System.IO.IOException: 源路徑和目標(biāo)路徑必須具有相同的根。移動(dòng)操作在卷之間無(wú)效。 在
System.IO.Directory.Move(String sourceDirName, String destDirName) 在 CreateDirectory.MoveButton_Click(Object sender, EventArgs e) )
try
...{
if (!System.IO.Directory.Exists(SDirectoryTextBox.Text))
...{
Label1.Text = "源文件夾不存在!";
return;
}
if (System.IO.Directory.Exists(DDirectoryTextBox.Text))
...{
Label1.Text = "目標(biāo)文件夾已經(jīng)存在!";
return;
}
System.IO.Directory.Move(SDirectoryTextBox.Text, DDirectoryTextBox.Text);
Label1.Text = "文件夾移動(dòng)成功! 源文件已經(jīng)被移除。目標(biāo)文件夾為" + DFileTextBox.Text;
}
catch (Exception ee)
...{
Label1.Text = "操作失??! 失敗原因:" + ee.ToString();
}
四、文件夾列表
<table border="1">
<tr>
<td colspan="2" style="color: #660066;">
文件夾中文件列表:
</td>
</tr>
<tr>
<td style="font-size: 10pt">
請(qǐng)輸入要?jiǎng)h除文件的路徑:
</td>
<td style="width: 158px">
<asp:TextBox ID="DirectoryTextBox" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Label ID="MsgLabel" runat="server" ForeColor="red"></asp:Label>
</td>
</tr>
<tr>
<td colspan="2" style="width: 158px">
<asp:ListBox ID="FileListBox" runat="server" Height="192px" Width="184px"></asp:ListBox>
</td>
</tr>
<tr>
<td align="center" colspan="2">
<asp:Button ID="ExistButton" runat="server" Text="確定" OnClick="ExistButton_Click" />
</td>
</tr>
</table>
更多信息請(qǐng)查看IT技術(shù)專(zhuān)欄