zoukankan      html  css  js  c++  java
  • C#对文件夹的判断、创建、移动、删除

    C#对文件夹的判断、创建、移动、删除
    判断文件夹是否存在
     

    DirectoryInfo类用于复制、移动、重命名、创建和删除目录等典型操作。用Directory类的Exists 方法可以简单快速的判

    断文件夹是否存在,参数是文件的路径。返回值是Boolean型。返回True说明文件夹存在,返回False说明文件夹不存

    在。

    例如,判断E盘下是否存在名为soft的文件夹。代码如下所示:

     

    Directory.Exists("E://soft ");
    创建文件夹
     

    通过DirectoryInfo类的Create 方法可以方便地创建文件夹。参数是将要创建的文件夹路径。返回值是一个由参数

    定的DirectoryInfo对象。

    本例演示了通过Directory类的Create 方法来创建文件夹

     

    程序代码如下:

     

     

        protected void Button1_Click(object sender, EventArgs e) 
        { 
            string Name = 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类的MoveTo方法可以对文件夹方便地进行移动。在移动的过程中会将目录及其内容一起移动,

    第一个参数是要移动的文件或目录的路径,第二个参数是文件夹的新路径。

    本例演示了通过DirectoryInfo类的MoveTo 方法移动文件夹

     

    程序代码如下:

        protected void Button1_Click(object sender, EventArgs e) 
        { 
            DirectoryInfo di = new DirectoryInfo(TextBox1.Text.ToString()); 
            DirectoryInfo di2 = new DirectoryInfo(TextBox2.Text.ToString()); 
            if (!di.Exists) 
            { 
                Label1.Text = "源文件夹不存在"; 
                return;         
            } 
            if (di2.Exists) 
            { 
                Label1.Text = "目标文件夹已经存在"; 
                return; 
            } 
            di.MoveTo(TextBox2.Text.ToString()); 
        }
    删除文件夹
     

    DirectoryInfo类的Delete方法可以用来删除文件夹。参数是要删除的文件夹的路径。

    本例演示了通过DirectoryInfo类的Delete方法删除文件夹

     

    程序代码如下:

            try 
            { 
                DirectoryInfo di = new DirectoryInfo(TextBox1.Text.ToString()); 
                if (di.Exists) 
                { 
                    di.Delete(); 
                    Label1.Text = "删除成功"; 
                } 
                else 
                { 
                    Label1.Text = "文件夹不存在"; 
                    return; 
                } 
            } 
            catch (Exception ex) 
            { 
                Label1.Text = "失败原因:" + ex.ToString(); 
            }
  • 相关阅读:
    大型web系统数据缓存设计
    配置AndroidStudio
    android-studio 安装gradle
    Gradle的简介与安装
    史上最详细的Android Studio系列教程四--Gradle基础
    Android SDK
    如何让猎头找到你
    android-volley-manager
    Android Studio导入Project的方法
    设置Android Studio启动时可选最近打开过的工程
  • 原文地址:https://www.cnblogs.com/zhihai/p/2343521.html
Copyright © 2011-2022 走看看