ASP.NET学习之对文件和文件夹的操作

今天是圣诞,先祝福大家圣诞快乐吧:)
[em02]一个人的精彩,呵呵.

先把这次的源文件包打包丢上来先.

源文件下载
下载文件 点击下载此文件的源代码
教程下载:
鼠标右键->目标另存为

Flash查看:
Flash动画



SoftWare: Visual Studio.Net 2005  EditPlus
System: winXP profession sp2

ASP.NET对文件和文件夹的操作没有想象中的复杂,我们对其操作主要是文件的删除,创建,移动,复制等几个功能操作吧.我们主要用到的是一个File类或FileStream类里面的操作。由于File类本身就提供了相关的操作方法,我们其实要做的就是一个调用就可以了。我们常用到的方法有以下:

File.copy() 复制一个文件
File.Move() 移动一个文件
File.Delete() 删除一个文件
File.CreateText() 创建一个文本文件
File.Open() 打开一个文件
File.Exists() 判断文件存不存在
File.OpenText() 读取文件文件中的内容

而我们常用的对象主要是 StreamReader 与StreamWriter 这两个了,他们的介绍大家看MSDN就可以知道了
ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.NETDEVFX.v20.chs/cpref8/html/T_System_IO_StreamReader_Members.htm#seeAlsoToggle
ms-help://MS.VSCC.v80/MS.MSDN.v80/MS.NETDEVFX.v20.chs/cpref8/html/T_System_IO_StreamWriter.htm

通过上面的这些方法,就可以实现对文件的操作了


1.创建一个文本文件



///
    /// 创建一个文件,利用StreamWriter
    ///

    protected void CreatText()
    {
        try
        {
            //建立一个StreamWrite对象
            StreamWriter objStreamWriter = File.CreateText(Server.MapPath(".") + "/My.txt");
            //利用writeLine()写入文件内容
            objStreamWriter.WriteLine(txtFileCotent.Text);
            objStreamWriter.Flush();//将缓存写入文件
            objStreamWriter.Close(); //关闭
            txtFileCotent.Text = "已经成功创建了一个文件";

            objStreamWriter.Close();
        }
        catch (Exception e)
        {
            Console.Write(e.Message);
        }
    }



2.删除一个文件

///
    /// 删除一个文件
    ///

    protected void DeleteFile()
    {
        try
        {
            string FileName = Server.MapPath(".") + "/" + txtFileName.Text.Trim();

            if (File.Exists(FileName))
            {
                File.Delete(FileName);

                lblDelete.Text = "文件删除成功";

            }
            else
            {
                lblDelete.Text = "文件不存在,删除不成功";
            }
        }
        catch (Exception e)
        {
            Console.Write(e.Message);
        }
    }



3.复制一个文件


///
    /// 复制文件 在运行此操作时,需要把项目中的CopyC.txt给删除.或者在File.Copy()方法中设置一个参数true.
    ///

    protected void CopyFile()
    {
        try
        {
        //要COPY的文件名
        string CopyFileName = Server.MapPath(".") + "/c.txt";
        //新的文件名,用来存储COPY过来的内容
        string NewFileName = Server.MapPath(".") + "/copyC.txt";

        //判定两个文件是否存在
        if (File.Exists(CopyFileName))
        {
          

            //将copyFileName的文件内容copy至NewFileName中

            File.Copy(CopyFileName, NewFileName);

           //显示结果
            lblCopyFile.Text="复制成功";

        }
        else
        {
            Console.Write("操作不成功,当前有一个文件不存在.");
        }
        }
        catch(Exception e)
        {
            Console.Write(e.Message);
        }
    }


4.移动一个文件


    protected void MoveFile()
    {
        try
        {
            string MoveFileName = Server.MapPath(".") + "/MoveFileName.txt";//这个是要移动的源文件名
            string NewFileName = Server.MapPath(".") + "/MoveAimFileName.txt";//新文件

            if (File.Exists(MoveFileName)) //判断文件是否存在
            {
                File.Move(MoveFileName, NewFileName);//使用移动方法move()

                lblMoveFile.Text = "移动文件成功,请查看新文件";

            }
            else
            {
                lblMoveFile.Text = "操作有误,文件不存在";

            }
        }
        catch (Exception e)
        {
            Console.Write(e.Message);
        }
    }


最后提醒你:不要忘记引用
using System.IO;
using System.Text;

上面是对文件的操作,你可以下载源文件来看下吧.我们还可以对文件夹进行相同的操作,同样要引用System.IO这个命名空间,在代码中为了方便,我把对文件夹的操作单独放到一个类里面去了.通过引用对象实现的相同的新建、查看、删除等相关的操作.我们主要是用到了DirectInfo类,它有以下的方法
DirectoryInfo.Create() 创建一个新的目录
DirectoryInfo.Delete() 删除一个新的目录
DirectoryInfo.Exists()  判断一个目录是否存在
DirectoryInfo.GetFiles() 获取当前目录的文件
DirectoryInfo.MoveTo() 移动一个新的目录

这里只是列举了最常用的一些方法.


1.创建一个新的文件夹


///
    /// 创建一个新的文件夹
    ///

    ///
    ///
    public string CreateFolder(string FolderName)
    {


        if (!Directory.Exists(FolderName))
        {
            Directory.CreateDirectory(FolderName);
            return "创建文件成功";
        }
        else
        {
            return "文件夹已存在";
        }
      
    }


2.删除一个文件夹

    ///
    /// 删除一个文件夹
    ///

    ///
    ///
    public string DeleteFolder(string FolderName)
    {
        try
        {
            // 检查目标目录是否以目录分割字符结束如果不是则添加之
            if (FolderName[FolderName.Length - 1] != Path.DirectorySeparatorChar)
                FolderName += Path.DirectorySeparatorChar;
            // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
            // 如果你指向Delete目标文件下面的文件而不包含目录请使用下面的方法
            // string[] fileList = Directory.GetFiles(FolderName);
            string[] fileList = Directory.GetFileSystemEntries(FolderName);
            // 遍历所有的文件和目录
            foreach (string file in fileList)
            {
                // 先当作目录处理如果存在这个目录就递归Delete该目录下面的文件
                if (Directory.Exists(file))
                {
                    DeleteFolder(FolderName + Path.GetFileName(file));
                }
                // 否则直接Delete文件
                else
                {
                    File.Delete(FolderName + Path.GetFileName(file));
                }
            }
            //删除文件夹
            System.IO.Directory.Delete(FolderName, true);

            
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
    return "删除成功";
    }



3.复制文件夹


///
    /// 复制文件夹下面的所有内容copy到目标文件夹下面
    ///

    ///
    ///
    ///
    public string CopyFolder(string srcPath, string aimPath)
    {
        try
        {
            if(!Directory.Exists(srcPath))
            {
                return "文件夹不存在";
            }
            else
            {
            // 检查目标目录是否以目录分割字符结束如果不是则添加之
            if (aimPath[aimPath.Length - 1] != Path.DirectorySeparatorChar)
                aimPath += Path.DirectorySeparatorChar;
            // 判断目标目录是否存在如果不存在则新建之
            if (!Directory.Exists(aimPath)) Directory.CreateDirectory(aimPath);
            // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组
            // 如果你指向copy目标文件下面的文件而不包含目录请使用下面的方法
            // string[] fileList = Directory.GetFiles(srcPath);
            string[] fileList = Directory.GetFileSystemEntries(srcPath);
            // 遍历所有的文件和目录
            foreach (string file in fileList)
            {
                // 先当作目录处理如果存在这个目录就递归Copy该目录下面的文件
                if (Directory.Exists(file))
                    CopyFolder(file, aimPath + Path.GetFileName(file));
                // 否则直接Copy文件
                else
                    File.Copy(file, aimPath + Path.GetFileName(file), true);
            }

            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }
        
        return "复制成功";

    }



4.得到一个文件夹中的子文件夹

///
    /// 得到一个文件夹下的所有文件夹及子文件夹
    ///

    ///
    ///
    public long ListAllFolder(string Path)
    {
        long dirSize = 0;
        DirectoryInfo dir = new DirectoryInfo(Path);

        // add the size of each file
        foreach (FileInfo file in dir.GetFiles())
            dirSize += file.Length;
        // add the size of each sub-directory, that is retrieved by recursively
        // calling this same routine
        foreach (DirectoryInfo subdir in dir.GetDirectories())
            dirSize += ListAllFolder(subdir.FullName);

        return dirSize;

    }


5.显示当前文件夹中的文件名

///
    /// 属性显示当前目录中的文件名
    ///

    ///
    public void ListAllFile(string path)
    {

        string FileList;
        // Create a reference to the current directory.
        DirectoryInfo di = new DirectoryInfo(Environment.CurrentDirectory);
        // Create an array representing the files in the current directory.
        FileInfo[] fi = di.GetFiles();
        Console.WriteLine("The following files exist in the current directory:");
        // Print out the names of the files in the current directory.
        foreach (FileInfo fiTemp in fi)
            System.Web.HttpContext.Current.Response.Write(fiTemp.Name);

    }



在网上搜到一个对文件夹和文件操作的类,其实跟自己的大同小异,不过还是方便大家,把它引过来了


using System;
using System.IO;
using System.Web;

namespace FolderBehavior
{
    /**////
    /// 对文件和文件夹的操作类
    ///

    public class FileControl
    {
        public FileControl()
        {
            
        }
        /**////
        /// 在根目录下创建文件夹
        ///

        /// 要创建的文件路径
        public void CreateFolder(string FolderPathName)
        {
            //判断文件夹是否存在
            if(FolderPathName.Trim().Length>0)
            {
                try
                {
                    string CreatePath = System.Web.HttpContext.Current.Server.MapPath

("../../../Images/"+FolderPathName).ToString();
                    if(!Directory.Exists(CreatePath))
                    {
                        Directory.CreateDirectory(CreatePath);
                    }      
                }
                catch
                {
                    throw;
                }
            }
        }

        /**////
        /// 删除一个文件夹下面的字文件夹和文件
        ///

        ///
        public void DeleteChildFolder(string FolderPathName)
        {
            if(FolderPathName.Trim().Length>0)
            {
                try
                {
                    string CreatePath = System.Web.HttpContext.Current.Server.MapPath

(FolderPathName).ToString();
                    if(Directory.Exists(CreatePath))
                    {
                        Directory.Delete(CreatePath,true);
                    }      
                }
                catch
                {
                    throw;
                }
            }
        }

        /**////
        /// 删除一个文件
        ///

        ///
        public void DeleteFile(string FilePathName)
        {
            try
            {
                FileInfo DeleFile = new FileInfo(System.Web.HttpContext.Current.Server.MapPath

(FilePathName).ToString());
                DeleFile.Delete();
            }
            catch
            {
            }
        }
        public void CreateFile(string FilePathName)
        {
            try
            {
                //创建文件夹
                string[] strPath= FilePathName.Split('/');
                CreateFolder(FilePathName.Replace("/" + strPath[strPath.Length-1].ToString(),"")); //创建文件


                FileInfo CreateFile =new FileInfo(System.Web.HttpContext.Current.Server.MapPath

(FilePathName).ToString());         //创建文件
                if(!CreateFile.Exists)
                {
                    FileStream FS=CreateFile.Create();      
                    FS.Close();
                }
            }
            catch
            {
            }
        }
        /**////
        /// 删除整个文件夹及其字文件夹和文件
        ///

        ///
        public void DeleParentFolder(string FolderPathName)
        {
            try
            {
                DirectoryInfo DelFolder = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath

(FolderPathName).ToString());
                if(DelFolder.Exists)
                {
                    DelFolder.Delete();  
                }
            }
            catch
            {
            }
        }
        /**////
        /// 在文件里追加内容
        ///

        ///
        public void ReWriteReadinnerText(string FilePathName,string WriteWord)
        {
            try
            {
                //建立文件夹和文件
                //CreateFolder(FilePathName);
                CreateFile(FilePathName);
                //得到原来文件的内容
                FileStream FileRead=new FileStream(System.Web.HttpContext.Current.Server.MapPath

(FilePathName).ToString(),FileMode.Open,FileAccess.ReadWrite);
                StreamReader FileReadWord=new StreamReader(FileRead,System.Text.Encoding.Default);
                string OldString = FileReadWord.ReadToEnd().ToString();
                OldString = OldString + WriteWord;  
                //把新的内容重新写入
                StreamWriter FileWrite=new StreamWriter(FileRead,System.Text.Encoding.Default);
                FileWrite.Write(WriteWord);
                //关闭
                FileWrite.Close();
                FileReadWord.Close();
                FileRead.Close();
            }
            catch
            {
                //    throw;
            }
        }

        /**////
        /// 在文件里追加内容
        ///

        ///
        public string ReaderFileData(string FilePathName)
        {
            try
            {
    
                FileStream FileRead=new FileStream(System.Web.HttpContext.Current.Server.MapPath

(FilePathName).ToString(),FileMode.Open,FileAccess.Read);
                StreamReader FileReadWord=new StreamReader(FileRead,System.Text.Encoding.Default);
                string TxtString = FileReadWord.ReadToEnd().ToString();                
                //关闭
                FileReadWord.Close();
                FileRead.Close();
                return TxtString;
            }
            catch
            {
                throw;
            }
        }
        /**////
        /// 读取文件夹的文件
        ///

        ///
        ///
        public DirectoryInfo checkValidSessionPath(string FilePathName)
        {                
            try
            {
                DirectoryInfo MainDir = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath

(FilePathName));
                return MainDir;    
                
            }
            catch
            {
                throw;
            }
        }
    }
}




其实以上这些大家只要查看MSDN就可以了,大多数都有相对应的例子的。

水平有限,请大家多多指教!




上一篇: 统计出表中或数组中每个重复项出现的次数
下一篇: 《聆听》杂志第二期(2007.2)
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags:
相关日志:
评论: 0 | 引用: 348 | 查看次数: 44270
发表评论
昵 称:
密 码: 游客发言不需要密码.
邮 箱: 邮件地址支持Gravatar头像,邮箱地址不会公开.
网 址: 输入网址便于回访.
内 容:
验证码:
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 30 字 | UBB代码 关闭 | [img]标签 关闭