ASP.NET創(chuàng)建、刪除和移動文件夾及文件夾列表功能

字號:


    本文采用C#語言實現(xiàn)創(chuàng)建,刪除和移動文件夾以及文件夾列表的功能,代碼如下:
    使用Directory類和DirectoryInfo類
    一、創(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)建時間為:" + 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();
    }
    三、移動文件夾
    源文件夾和目標文件夾要求存在于同一個硬盤分區(qū)中否則會操作失?。ú僮魇。?失敗原因:System.IO.IOException: 源路徑和目標路徑必須具有相同的根。移動操作在卷之間無效。 在
    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 = "目標文件夾已經(jīng)存在!";
    return;
    }
    System.IO.Directory.Move(SDirectoryTextBox.Text, DDirectoryTextBox.Text);
    Label1.Text = "文件夾移動成功! 源文件已經(jīng)被移除。目標文件夾為" + DFileTextBox.Text;
    }
    catch (Exception ee)
    ...{
    Label1.Text = "操作失??! 失敗原因:" + ee.ToString();
    }
    四、文件夾列表
    <table>
    <tr>
    <td colspan="2">
    文件夾中文件列表:
    </td>
    </tr>
    <tr>
    <td>
    請輸入要刪除文件的路徑:
    </td>
    <td>
    <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">
    <asp:ListBox ID="FileListBox" runat="server" Height="192px" Width="184px"></asp:ListBox>
    </td>
    </tr>
    <tr>
    <td colspan="2">
    <asp:Button ID="ExistButton" runat="server" Text="確定" OnClick="ExistButton_Click" />
    </td>
    </tr>
    </table>