首页 游戏 软件 排行 智能

Asp.net(C#)文件操作函数大全(读取,删除,批量拷贝,删除...)

来源: 西西整理 日期:2014/9/20 9:44:56

对于文件流的操作,首先你得引用命名空间:using System.IO;对文件的操作主要指两方面:第一,是对文件本身进行操作;第二,是对文件内容进行操作。
如果是前者,楼主可以使用System.IO.FileInfo等类型,对文件进行操作;后者的话可以通过System.IO.StreamReader,StreamWriter,FileStreamd等流对象对文件内容进行操作。

Asp.net(C#)对文件操作的方法(读取,删除,批量拷贝,删除...)

using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.IO;
namespace EC
{
    /// <summary>
    /// FileObj 的摘要说明
    /// </summary>
    public class FileObj
    {
        构造函数

        IDisposable 成员

        取得文件后缀名

        #region 写文件
        /****************************************
        * 函数名称:WriteFile
        * 功能说明:当文件不存时,则创建文件,并追加文件
        * 参    数:Path:文件路径,Strings:文本内容
        * 调用示列:
        *          string Path = Server.MapPath("Default2.aspx");      
        *          string Strings = "这是我写的内容啊";
        *          EC.FileObj.WriteFile(Path,Strings);
        *****************************************/
        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <param name="Strings">文件内容</param>
        public static void WriteFile(string Path, string Strings)
        {

            if (!System.IO.File.Exists(Path))
            {
                //Directory.CreateDirectory(Path);

                System.IO.FileStream f = System.IO.File.Create(Path);
                f.Close();
                f.Dispose();
            }
            System.IO.StreamWriter f2 = new System.IO.StreamWriter(Path, true, System.Text.Encoding.UTF8);
            f2.WriteLine(Strings);
            f2.Close();
            f2.Dispose();


        }
        #endregion

        #region 读文件
        /****************************************
        * 函数名称:ReadFile
        * 功能说明:读取文本内容
        * 参    数:Path:文件路径
        * 调用示列:
        *          string Path = Server.MapPath("Default2.aspx");      
        *          string s = EC.FileObj.ReadFile(Path);
        *****************************************/
        /// <summary>
        /// 读文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <returns></returns>
        public static string ReadFile(string Path)
        {
            string s = "";
            if (!System.IO.File.Exists(Path))
                s = "不存在相应的目录";
            else
            {
                StreamReader f2 = new StreamReader(Path, System.Text.Encoding.GetEncoding("gb2312"));
                s = f2.ReadToEnd();
                f2.Close();
                f2.Dispose();
            }

            return s;
        }
        #endregion

        #region 追加文件
        /****************************************
        * 函数名称:FileAdd
        * 功能说明:追加文件内容
        * 参    数:Path:文件路径,strings:内容
        * 调用示列:
        *          string Path = Server.MapPath("Default2.aspx");    
        *          string Strings = "新追加内容";
        *          EC.FileObj.FileAdd(Path, Strings);
        *****************************************/
        /// <summary>
        /// 追加文件
        /// </summary>
        /// <param name="Path">文件路径</param>
        /// <param name="strings">内容</param>
        public static void FileAdd(string Path, string strings)
        {
            StreamWriter sw = File.AppendText(Path);
            sw.Write(strings);
            sw.Flush();
            sw.Close();
            sw.Dispose();
        }
        #endregion

        #region 拷贝文件
        /****************************************
        * 函数名称:FileCoppy
        * 功能说明:拷贝文件
        * 参    数:OrignFile:原始文件,NewFile:新文件路径
        * 调用示列:
        *          string OrignFile = Server.MapPath("Default2.aspx");    
        *          string NewFile = Server.MapPath("Default3.aspx");
        *          EC.FileObj.FileCoppy(OrignFile, NewFile);
        *****************************************/
        /// <summary>
        /// 拷贝文件
        /// </summary>
        /// <param name="OrignFile">原始文件</param>
        /// <param name="NewFile">新文件路径</param>
        public static void FileCoppy(string OrignFile, string NewFile)
        {
            File.Copy(OrignFile, NewFile, true);
        }

        #endregion

        #region 删除文件
        /****************************************
        * 函数名称:FileDel
        * 功能说明:删除文件
        * 参    数:Path:文件路径
        * 调用示列:
        *          string Path = Server.MapPath("Default3.aspx");    
        *          EC.FileObj.FileDel(Path);
        *****************************************/
        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="Path">路径</param>
        public static void FileDel(string Path)
        {
            File.Delete(Path);
        }
        #endregion

        #region 移动文件
        /****************************************
        * 函数名称:FileMove
        * 功能说明:移动文件
        * 参    数:OrignFile:原始路径,NewFile:新文件路径
        * 调用示列:
        *            string OrignFile = Server.MapPath("../说明.txt");    
        *            string NewFile = Server.MapPath("../../说明.txt");
        *            EC.FileObj.FileMove(OrignFile, NewFile);
        *****************************************/
        /// <summary>
        /// 移动文件
        /// </summary>
        /// <param name="OrignFile">原始路径</param>
        /// <param name="NewFile">新路径</param>
        public static void FileMove(string OrignFile, string NewFile)
        {
            File.Move(OrignFile, NewFile);
        }
        #endregion

        #region 在当前目录下创建目录
        /****************************************
        * 函数名称:FolderCreate
        * 功能说明:在当前目录下创建目录
        * 参    数:OrignFolder:当前目录,NewFloder:新目录
        * 调用示列:
        *          string OrignFolder = Server.MapPath("test/");    
        *          string NewFloder = "new";
        *          EC.FileObj.FolderCreate(OrignFolder, NewFloder); 
        *****************************************/
        /// <summary>
        /// 在当前目录下创建目录
        /// </summary>
        /// <param name="OrignFolder">当前目录</param>
        /// <param name="NewFloder">新目录</param>
        public static void FolderCreate(string OrignFolder, string NewFloder)
        {
            Directory.SetCurrentDirectory(OrignFolder);
            Directory.CreateDirectory(NewFloder);
        }

        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="Path"></param>
        public static void FolderCreate(string Path)
        {
            // 判断目标目录是否存在如果不存在则新建之
            if (!Directory.Exists(Path))
                Directory.CreateDirectory(Path);
        }

        #endregion

        #region 创建目录
        public static void FileCreate(string Path)
        {
            FileInfo CreateFile = new FileInfo(Path); //创建文件 
            if (!CreateFile.Exists)
            {
                FileStream FS = CreateFile.Create();
                FS.Close();
            }
        }
        #endregion

        #region 递归删除文件夹目录及文件
        /****************************************
        * 函数名称:DeleteFolder
        * 功能说明:递归删除文件夹目录及文件
        * 参    数:dir:文件夹路径
        * 调用示列:
        *          string dir = Server.MapPath("test/");  
        *          EC.FileObj.DeleteFolder(dir);      
        *****************************************/
        /// <summary>
        /// 递归删除文件夹目录及文件
        /// </summary>
        /// <param name="dir"></param>  
        /// <returns></returns>
        public static void DeleteFolder(string dir)
        {
            if (Directory.Exists(dir)) //如果存在这个文件夹删除之 
            {
                foreach (string d in Directory.GetFileSystemEntries(dir))
                {
                    if (File.Exists(d))
                        File.Delete(d); //直接删除其中的文件                        
                    else
                        DeleteFolder(d); //递归删除子文件夹 
                }
                Directory.Delete(dir, true); //删除已空文件夹                
            }
        }

        #endregion

        #region 将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
        /****************************************
        * 函数名称:CopyDir
        * 功能说明:将指定文件夹下面的所有内容copy到目标文件夹下面 果目标文件夹为只读属性就会报错。
        * 参    数:srcPath:原始路径,aimPath:目标文件夹
        * 调用示列:
        *          string srcPath = Server.MapPath("test/");  
        *          string aimPath = Server.MapPath("test1/");
        *          EC.FileObj.CopyDir(srcPath,aimPath);  
        *****************************************/
        /// <summary>
        /// 指定文件夹下面的所有内容copy到目标文件夹下面
        /// </summary>
        /// <param name="srcPath">原始路径</param>
        /// <param name="aimPath">目标文件夹</param>
        public static void CopyDir(string srcPath, string aimPath)
        {
            try
            {
                // 检查目标目录是否以目录分割字符结束如果不是则添加之
                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))
                        CopyDir(file, aimPath + Path.GetFileName(file));
                    //否则直接Copy文件
                    else
                        File.Copy(file, aimPath + Path.GetFileName(file), true);
                }
            }
            catch (Exception ee)
            {
                throw new Exception(ee.ToString());
            }
        }
        #endregion

        #region 获取指定文件夹下所有子目录及文件(树形)
        /****************************************
        * 函数名称:GetFoldAll(string Path)
        * 功能说明:获取指定文件夹下所有子目录及文件(树形)
        * 参    数:Path:详细路径
        * 调用示列:
        *          string strDirlist = Server.MapPath("templates");      
        *          this.Literal1.Text = EC.FileObj.GetFoldAll(strDirlist);  
        *****************************************/
        /// <summary>
        /// 获取指定文件夹下所有子目录及文件
        /// </summary>
        /// <param name="Path">详细路径</param>
        public static string GetFoldAll(string Path)
        {

            string str = "";
            DirectoryInfo thisOne = new DirectoryInfo(Path);
            str = ListTreeShow(thisOne, 0, str);
            return str;

        }

        /// <summary>
        /// 获取指定文件夹下所有子目录及文件函数
        /// </summary>
        /// <param name="theDir">指定目录</param>
        /// <param name="nLevel">默认起始值,调用时,一般为0</param>
        /// <param name="Rn">用于迭加的传入值,一般为空</param>
        /// <returns></returns>
        public static string ListTreeShow(DirectoryInfo theDir, int nLevel, string Rn)//递归目录 文件
        {
            DirectoryInfo[] subDirectories = theDir.GetDirectories();//获得目录
            foreach (DirectoryInfo dirinfo in subDirectories)
            {

                if (nLevel == 0)
                {
                    Rn += "├";
                }
                else
                {
                    string _s = "";
                    for (int i = 1; i <= nLevel; i++)
                    {
                        _s += "│&nbsp;";
                    }
                    Rn += _s + "├";
                }
                Rn += "<b>" + dirinfo.Name.ToString() + "</b><br />";
                FileInfo[] fileInfo = dirinfo.GetFiles();  //目录下的文件
                foreach (FileInfo fInfo in fileInfo)
                {
                    if (nLevel == 0)
                    {
                        Rn += "│&nbsp;├";
                    }
                    else
                    {
                        string _f = "";
                        for (int i = 1; i <= nLevel; i++)
                        {
                            _f += "│&nbsp;";
                        }
                        Rn += _f + "│&nbsp;├";
                    }
                    Rn += fInfo.Name.ToString() + " <br />";
                }
                Rn = ListTreeShow(dirinfo, nLevel + 1, Rn);


            }
            return Rn;
        }



        /****************************************
        * 函数名称:GetFoldAll(string Path)
        * 功能说明:获取指定文件夹下所有子目录及文件(下拉框形)
        * 参    数:Path:详细路径
        * 调用示列:
        *            string strDirlist = Server.MapPath("templates");      
        *            this.Literal2.Text = EC.FileObj.GetFoldAll(strDirlist,"tpl","");
        *****************************************/
        /// <summary>
        /// 获取指定文件夹下所有子目录及文件(下拉框形)
        /// </summary>
        /// <param name="Path">详细路径</param>
        ///<param name="DropName">下拉列表名称</param>
        ///<param name="tplPath">默认选择模板名称</param>
        public static string GetFoldAll(string Path,string DropName,string tplPath)
        {
            string strDrop = "<select name="" + DropName + "" id="" + DropName + ""><option value="">--请选择详细模板--</option>";
            string str = "";
            DirectoryInfo thisOne = new DirectoryInfo(Path);
            str = ListTreeShow(thisOne, 0, str,tplPath);
            return strDrop+str+"</select>";

        }

        /// <summary>
        /// 获取指定文件夹下所有子目录及文件函数
        /// </summary>
        /// <param name="theDir">指定目录</param>
        /// <param name="nLevel">默认起始值,调用时,一般为0</param>
        /// <param name="Rn">用于迭加的传入值,一般为空</param>
        /// <param name="tplPath">默认选择模板名称</param>
        /// <returns></returns>
        public static string ListTreeShow(DirectoryInfo theDir, int nLevel, string Rn,string tplPath)//递归目录 文件
        {
            DirectoryInfo[] subDirectories = theDir.GetDirectories();//获得目录

            foreach (DirectoryInfo dirinfo in subDirectories)
            {

                Rn += "<option value="" + dirinfo.Name.ToString() + """;
                if (tplPath.ToLower() == dirinfo.Name.ToString().ToLower())
                {
                    Rn += " selected ";
                }
                Rn += ">";

                if (nLevel == 0)
                {
                    Rn += "┣";
                }
                else
                {
                    string _s = "";
                    for (int i = 1; i <= nLevel; i++)
                    {
                        _s += "│&nbsp;";
                    }
                    Rn += _s + "┣";
                }
                Rn += "" + dirinfo.Name.ToString() + "</option>";


                FileInfo[] fileInfo = dirinfo.GetFiles();  //目录下的文件
                foreach (FileInfo fInfo in fileInfo)
                {
                    Rn += "<option value="" + dirinfo.Name.ToString()+"/"+fInfo.Name.ToString() + """;
                    if (tplPath.ToLower() == fInfo.Name.ToString().ToLower())
                    {
                        Rn += " selected ";
                    }
                    Rn += ">";

                    if (nLevel == 0)
                    {
                        Rn += "│&nbsp;├";
                    }
                    else
                    {
                        string _f = "";
                        for (int i = 1; i <= nLevel; i++)
                        {
                            _f += "│&nbsp;";
                        }
                        Rn += _f + "│&nbsp;├";
                    }
                    Rn += fInfo.Name.ToString() + "</option>";
                }
                Rn = ListTreeShow(dirinfo, nLevel + 1, Rn, tplPath);


            }
            return Rn;
        }
        #endregion

        #region 获取文件夹大小
        /****************************************
        * 函数名称:GetDirectoryLength(string dirPath)
        * 功能说明:获取文件夹大小
        * 参    数:dirPath:文件夹详细路径
        * 调用示列:
        *          string Path = Server.MapPath("templates"); 
        *          Response.Write(EC.FileObj.GetDirectoryLength(Path));      
        *****************************************/
        /// <summary>
        /// 获取文件夹大小
        /// </summary>
        /// <param name="dirPath">文件夹路径</param>
        /// <returns></returns>
        public static long GetDirectoryLength(string dirPath)
        {
            if (!Directory.Exists(dirPath))
                return 0;
            long len = 0;
            DirectoryInfo di = new DirectoryInfo(dirPath);
            foreach (FileInfo fi in di.GetFiles())
            {
                len += fi.Length;
            }
            DirectoryInfo[] dis = di.GetDirectories();
            if (dis.Length > 0)
            {
                for (int i = 0; i < dis.Length; i++)
                {
                    len += GetDirectoryLength(dis.FullName);
                }
            }
            return len;
        }
        #endregion

        #region 获取指定文件详细属性
        /****************************************
        * 函数名称:GetFileAttibe(string filePath)
        * 功能说明:获取指定文件详细属性
        * 参    数:filePath:文件详细路径
        * 调用示列:
        * string file = Server.MapPath("robots.txt");  
        * Response.Write(EC.FileObj.GetFileAttibe(file));        
        *****************************************/
        /// <summary>
        /// 获取指定文件详细属性
        /// </summary>
        /// <param name="filePath">文件详细路径</param>
        /// <returns></returns>
        public static string GetFileAttibe(string filePath)
        {
            string str = "";
            System.IO.FileInfo objFI = new System.IO.FileInfo(filePath);
            str += "详细路径:" + objFI.FullName + "<br>文件名称:" + objFI.Name + "<br>文件长度:" + objFI.Length.ToString() + "字节<br>创建时间" + objFI.CreationTime.ToString() + "<br>最后访问时间:" + objFI.LastAccessTime.ToString() + "<br>修改时间:" + objFI.LastWriteTime.ToString() + "<br>所在目录:" + objFI.DirectoryName + "<br>扩展名:" + objFI.Extension;
            return str;
        }
        #endregion
    }

目录操作
System.IO 类

目录操作
string[] drives = Directory.GetLogicalDrives();   //本地驱动器的名,如:C:\等
string path = Directory.GetCurrentDirectory();  //获取应用程序的当前工作目录
Path.GetFileName(@"c:\dir\file.txt");              //获取子目录的名字,result的结果是file.txt
Directory.GetFiles(路径及文件名)                     //获取指定目录中的文件名(文件列表)
DirectoryInfo di = new DirectoryInfo(@"f:\MyDir");      //构造函数创建目录
DirectoryInfo di=Directory.CreateDirectory(@"f:\bbs"); //创建对象并创建目录
if (di.Exists == false)                                    //检查是否存在此目录
di.Create();                                                //创建目录
DirectoryInfo dis = di.CreateSubdirectory("SubDir");    //以相对路径创建子目录
dis.Delete(true);                                         //删除刚创建的子目录
di.Delete(true);                                          //删除创建目录

文件操作
Directory.Delete(@"f:\bbs2", true); //删除目录及其子目录和内容(如为假不能删除有内容的目录包括子目录)
Directory.GetDirectories 方法 //获取指定目录中子目录的名称
string[] dirs = Directory.GetDirectories(@"f:\", "b*"); 
Console.WriteLine("此目录中以b开头的子目录共{0}个!", dirs.Length);
foreach (string dir in dirs) { Console.WriteLine(dir); }
Directory.GetFileSystemEntries //获取指定目录中的目录及文件名
Directory.GetLogicalDrives //检索此计算机上格式为“<驱动器号>:\”的逻辑驱动器的名称,【语法同上】
Directory.GetParent //用于检索父目录的路径。
DirectoryInfo a = Directory.GetParent(path);
Console.WriteLine(a.FullName);Directory.Move //移动目录及其在内的所有文件
Directory.Move(@"f:\bbs\1", @"f:\bbs\2"); //将文件夹1内的文件剪到文件夹2内 文件夹2是刚创建的 

Stream // 对字节的读写操作(包含对异步操作的支持) Reading Writing Seeking

BinaryReader和BinaryWriter // 从字符串或原始数据到各种流之间的读写操作

FileStream类通过Seek()方法进行对文件的随机访问,默认为同步

TextReader和TextWriter //用于gb2312字符的输入和输出

StringReader和StringWriter //在字符串中读写字符

StreamReader和StreamWriter //在流中读写字符

BufferedStream 为诸如网络流的其它流添加缓冲的一种流类型.

MemoryStream 无缓冲的流

NetworkStream 互联网络上的流

//编码转换  

Encoding e1 = Encoding.Default;               //取得本页默认代码   

Byte[] bytes = e1.GetBytes("中国人民解放军"); //转为二进制  

string str = Encoding.GetEncoding("UTF-8").GetString(bytes); //转回UTF-8编码  

//文本文件操作:创建/读取/拷贝/删除  

using System;  

using System.IO;  

class Test   

{  

   string path = @"f:\t.txt";  

   public static void Main()   

   {         

      //创建并写入(将覆盖已有文件)  

      if (!File.Exists(path))  

      {            

         using (StreamWriter sw = File.CreateText(path))  

         {  

            sw.WriteLine("Hello");  

         }   

      }  

      //读取文件  

      using (StreamReader sr = File.OpenText(path))   

      {  

        string s = "";  

        while ((s = sr.ReadLine()) != null)   

        {  

           Console.WriteLine(s);  

        }  

     }  

     //删除/拷贝  

     try   

     {  

        File.Delete(path);  

        File.Copy(path, @"f:\tt.txt");  

     }   

     catch (Exception e)   

     {  

        Console.WriteLine("The process failed: {0}", e.ToString());  

     }  

   }  

}  

//流文件操作  

private const string name = "Test.data";  

public static void Main(String[] args)   

{  

    //打开文件()  ,或通过File创建立如:fs = File.Create(path, 1024)  

    FileStream fs = new FileStream(name, FileMode.CreateNew);  

    //转换为字节 写入数据(可写入中文)  

    Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");  

    //字节数组,字节偏移量,最多写入的字节数  

    fs.Write(info, 0, info.Length);  

    w.Close();  

    fs.Close();  

    //打开文件  

    fs = new FileStream(name, FileMode.Open, FileAccess.Read);  

    //读取  

    BinaryReader r = new BinaryReader(fs);  

    for (int i = 0; i < 11; i++)   

    {  

        Console.WriteLine(r.ReadInt32());  

    }  

    w.Close();  

    fs.Close();  

}  

C#追加文件  

    StreamWriter sw = File.AppendText(Server.MapPath(".")+"\\myText.txt");   

    sw.WriteLine("追逐理想");   

    sw.WriteLine("kzlll");   

    sw.WriteLine(".NET笔记");   

    sw.Flush();   

    sw.Close();  

C#拷贝文件  

    string OrignFile,NewFile;   

    OrignFile = Server.MapPath(".")+"\\myText.txt";   

    NewFile = Server.MapPath(".")+"\\myTextCopy.txt";   

    File.Copy(OrignFile,NewFile,true);  

C#删除文件  

    string delFile = Server.MapPath(".")+"\\myTextCopy.txt";   

    File.Delete(delFile);  

C#移动文件  

    string OrignFile,NewFile;   

    OrignFile = Server.MapPath(".")+"\\myText.txt";   

    NewFile = Server.MapPath(".")+"\\myTextCopy.txt";   

    File.Move(OrignFile,NewFile);  

C#创建目录  

     // 创建目录c:\sixAge   

    DirectoryInfo d=Directory.CreateDirectory("c:\\sixAge");   

     // d1指向c:\sixAge\sixAge1   

    DirectoryInfo d1=d.CreateSubdirectory("sixAge1");   

     // d2指向c:\sixAge\sixAge1\sixAge1_1   

    DirectoryInfo d2=d1.CreateSubdirectory("sixAge1_1");   

     // 将当前目录设为c:\sixAge   

    Directory.SetCurrentDirectory("c:\\sixAge");   

     // 创建目录c:\sixAge\sixAge2   

    Directory.CreateDirectory("sixAge2");   

     // 创建目录c:\sixAge\sixAge2\sixAge2_1   

    Directory.CreateDirectory("sixAge2\\sixAge2_1");   

递归删除文件夹及文件  

  public void DeleteFolder(string dir)   

  {   

    if (Directory.Exists(dir)) //如果存在这个文件夹删除之   

    {   

      foreach(string d in Directory.GetFileSystemEntries(dir))   

      {   

        if(File.Exists(d))   

          File.Delete(d); //直接删除其中的文件   

        else   

          DeleteFolder(d); //递归删除子文件夹   

      }   

      Directory.Delete(dir); //删除已空文件夹   

      Response.Write(dir+" 文件夹删除成功");   

    }   

    else   

      Response.Write(dir+" 该文件夹不存在"); //如果文件夹不存在则提示   

  }   

  protected void Page_Load (Object sender ,EventArgs e)   

  {   

    string Dir="D:\\gbook\\11";   

    DeleteFolder(Dir); //调用函数删除文件夹   

  }  

copy文件夹内容  

实现一个静态方法将指定文件夹下面的所有内容copy到目标文件夹下面,如果目标文件夹为只读属性就会报错。    

  方法1.  

  public static void CopyDir(string srcPath,string aimPath)  

  {  

    try  

    {  

      // 检查目标目录是否以目录分割字符结束如果不是则添加之  

      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))  

          CopyDir(file,aimPath+Path.GetFileName(file));  

        // 否则直接Copy文件  

        else  

          File.Copy(file,aimPath+Path.GetFileName(file),true);  

      }  

    }  

    catch (Exception e)  

    {  

      MessageBox.Show (e.ToString());  

    }  

  }  

  方法2.  

  public static void CopyFolder(string strFromPath,string strToPath)  

  {  

    //如果源文件夹不存在,则创建  

    if (!Directory.Exists(strFromPath))  

    {   

      Directory.CreateDirectory(strFromPath);  

    }   

    //取得要拷贝的文件夹名  

    string strFolderName = strFromPath.Substring(strFromPath.LastIndexOf("\\") + 1,strFromPath.Length - strFromPath.LastIndexOf("\\") - 1);   

    //如果目标文件夹中没有源文件夹则在目标文件夹中创建源文件夹  

    if (!Directory.Exists(strToPath + "\\" + strFolderName))  

    {   

      Directory.CreateDirectory(strToPath + "\\" + strFolderName);  

    }  

    //创建数组保存源文件夹下的文件名  

    string[] strFiles = Directory.GetFiles(strFromPath);  

    //循环拷贝文件  

    for(int i = 0;i < strFiles.Length;i++)  

    {  

    //取得拷贝的文件名,只取文件名,地址截掉。  

    string strFileName = strFiles[i].Substring(strFiles[i].LastIndexOf("\\") + 1,strFiles[i].Length - strFiles[i].LastIndexOf("\\") - 1);  

    //开始拷贝文件,true表示覆盖同名文件  

    File.Copy(strFiles[i],strToPath + "\\" + strFolderName + "\\" + strFileName,true);  

    }  

    //创建DirectoryInfo实例  

    DirectoryInfo dirInfo = new DirectoryInfo(strFromPath);  

    //取得源文件夹下的所有子文件夹名称  

    DirectoryInfo[] ZiPath = dirInfo.GetDirectories();  

    for (int j = 0;j < ZiPath.Length;j++)  

    {  

      //获取所有子文件夹名  

      string strZiPath = strFromPath + "\\" + ZiPath[j].ToString();   

      //把得到的子文件夹当成新的源文件夹,从头开始新一轮的拷贝  

      CopyFolder(strZiPath,strToPath + "\\" + strFolderName);  

    }  

  }  

删除文件夹内容  

实现一个静态方法将指定文件夹下面的所有内容Detele,测试的时候要小心操作,删除之后无法恢复。  

  public static void DeleteDir(string aimPath)  

  {  

    try  

    {  

      // 检查目标目录是否以目录分割字符结束如果不是则添加之  

      if(aimPath[aimPath.Length-1] != Path.DirectorySeparatorChar)   

        aimPath += Path.DirectorySeparatorChar;  

      // 得到源目录的文件列表,该里面是包含文件以及目录路径的一个数组  

      // 如果你指向Delete目标文件下面的文件而不包含目录请使用下面的方法  

      // string[] fileList = Directory.GetFiles(aimPath);  

      string[] fileList = Directory.GetFileSystemEntries(aimPath);  

      // 遍历所有的文件和目录  

      foreach(string file in fileList)  

      {  

        // 先当作目录处理如果存在这个目录就递归Delete该目录下面的文件  

        if(Directory.Exists(file))  

        {  

          DeleteDir(aimPath+Path.GetFileName(file));  

        }  

        // 否则直接Delete文件  

        else  

        {  

          File.Delete (aimPath+Path.GetFileName(file));  

        }  

      }  

    //删除文件夹  

    System.IO .Directory .Delete (aimPath,true);  

    }  

    catch (Exception e)  

    {  

      MessageBox.Show (e.ToString());  

    }  

  }  

读取文本文件  

 private void ReadFromTxtFile()  

 {  

    if(filePath.PostedFile.FileName != "")  

    {  

      txtFilePath =filePath.PostedFile.FileName;  

      fileExtName = txtFilePath.Substring(txtFilePath.LastIndexOf(".")+1,3);  

      if(fileExtName !="txt" && fileExtName != "TXT")  

      {  

      Response.Write("请选择文本文件");  

      }  

      else  

      {  

      StreamReader fileStream = new StreamReader(txtFilePath,Encoding.Default);  

      txtContent.Text = fileStream.ReadToEnd();  

      fileStream.Close();  

     }  

    }  

  }  

获取文件列表  

看到动态表的影子,这个应该是从项目里面拷贝出来的。  

private void GetFileList()  

{  

  string strCurDir,FileName,FileExt;  

  /**////文件大小  

  long FileSize;  

  /**////最后修改时间;  

  DateTime FileModify;  

  /**////初始化  

  if(!IsPostBack)  

  {  

    /**////初始化时,默认为当前页面所在的目录  

    strCurDir = Server.MapPath(".");  

    lblCurDir.Text = strCurDir;  

    txtCurDir.Text = strCurDir;  

  }  

  else  

  {  

    strCurDir = txtCurDir.Text;  

    txtCurDir.Text = strCurDir;  

    lblCurDir.Text = strCurDir;  

  }  

  FileInfo fi;  

  DirectoryInfo dir;  

  TableCell td;  

  TableRow tr;  

  tr = new TableRow();  

  /**////动态添加单元格内容  

  td = new TableCell();  

  td.Controls.Add(new LiteralControl("文件名"));  

  tr.Cells.Add(td);  

  td = new TableCell();  

  td.Controls.Add(new LiteralControl("文件类型"));  

  tr.Cells.Add(td);  

  td = new TableCell();  

  td.Controls.Add(new LiteralControl("文件大小"));  

  tr.Cells.Add(td);  

  td = new TableCell();  

  td.Controls.Add(new LiteralControl("最后修改时间"));  

  tr.Cells.Add(td);  

  tableDirInfo.Rows.Add(tr);  

  /**////针对当前目录建立目录引用对象  

  DirectoryInfo dirInfo = new DirectoryInfo(txtCurDir.Text);  

  /**////循环判断当前目录下的文件和目录  

  foreach(FileSystemInfo fsi in dirInfo.GetFileSystemInfos())  

  {  

    FileName = "";  

    FileExt = "";  

    FileSize = 0;  

    /**////如果是文件  

    if(fsi is FileInfo)  

    {  

      fi = (FileInfo)fsi;  

      /**////取得文件名  

      FileName = fi.Name;  

      /**////取得文件的扩展名  

      FileExt = fi.Extension;  

      /**////取得文件的大小  

      FileSize = fi.Length;  

      /**////取得文件的最后修改时间  

      FileModify = fi.LastWriteTime;  

    }  

      /**////否则是目录  

    else  

    {  

      dir = (DirectoryInfo)fsi;  

      /**////取得目录名  

      FileName = dir.Name;  

      /**////取得目录的最后修改时间  

      FileModify = dir.LastWriteTime;  

      /**////设置文件的扩展名为"文件夹"  

      FileExt = "文件夹";  

    }  

    /**////动态添加表格内容  

    tr = new TableRow();  

    td = new TableCell();  

    td.Controls.Add(new LiteralControl(FileName));  

    tr.Cells.Add(td);  

    td = new TableCell();  

    td.Controls.Add(new LiteralControl(FileExt));  

    tr.Cells.Add(td);  

    td = new TableCell();  

    td.Controls.Add(new LiteralControl(FileSize.ToString()+"字节"));  

    tr.Cells.Add(td);  

    td = new TableCell();  

    td.Controls.Add(new LiteralControl(FileModify.ToString("yyyy-mm-dd hh:mm:ss")));  

    tr.Cells.Add(td);  

    tableDirInfo.Rows.Add(tr);  

  }  

}  

读取日志文件  

   private void ReadLogFile()  

   {  

     //从指定的目录以打开或者创建的形式读取日志文件  

    FileStream fs = new FileStream(Server.MapPath("upedFile")+"\\logfile.txt", FileMode.OpenOrCreate, FileAccess.Read);  

    //定义输出字符串  

    StringBuilder output = new StringBuilder();  

    //初始化该字符串的长度为0  

    output.Length = 0;  

    //为上面创建的文件流创建读取数据流  

    StreamReader read = new StreamReader(fs);  

    //设置当前流的起始位置为文件流的起始点  

    read.BaseStream.Seek(0, SeekOrigin.Begin);  

    //读取文件  

    while (read.Peek() > -1)   

    {  

      //取文件的一行内容并换行  

      output.Append(read.ReadLine() + "\n");  

    }  

    //关闭释放读数据流  

    read.Close();  

    //返回读到的日志文件内容  

    return output.ToString();  

  }  

写入日志文件  

  private void WriteLogFile(string input)  

  {   

    //指定日志文件的目录  

    string fname = Server.MapPath("upedFile") + "\\logfile.txt";  

    //定义文件信息对象  

    FileInfo finfo = new FileInfo(fname);  

    //判断文件是否存在以及是否大于2K  

    if ( finfo.Exists && finfo.Length > 2048 )  

    {  

      //删除该文件  

      finfo.Delete();  

    }  

    //创建只写文件流  

    using(FileStream fs = finfo.OpenWrite())  

    {  

      //根据上面创建的文件流创建写数据流  

      StreamWriter w = new StreamWriter(fs);  

      //设置写数据流的起始位置为文件流的末尾  

      w.BaseStream.Seek(0, SeekOrigin.End);  

      w.Write("\nLog Entry : ");  

      //写入当前系统时间并换行  

      w.Write("{0} {1} \r\n",DateTime.Now.ToLongTimeString(),DateTime.Now.ToLongDateString());  

      //写入日志内容并换行  

      w.Write(input + "\n");  

      //写入------------------------------------“并换行  

      w.Write("------------------------------------\n");  

      //清空缓冲区内容,并把缓冲区内容写入基础流  

      w.Flush();  

      //关闭写数据流  

      w.Close();  

    }  

  }  

C#创建HTML文件  

  private void CreateHtmlFile()  

  {   

    //定义和html标记数目一致的数组  

    string[] newContent = new string[5];  

    StringBuilder strhtml = new StringBuilder();  

    try   

    {  

      //创建StreamReader对象  

      using (StreamReader sr = new StreamReader(Server.MapPath("createHTML") + "\\template.html"))   

      {  

        String oneline;  

        //读取指定的HTML文件模板  

        while ((oneline = sr.ReadLine()) != null)   

        {  

          strhtml.Append(oneline);  

        }  

          sr.Close();  

      }  

    }  

    catch(Exception err)  

    {  

      //输出异常信息  

      Response.Write(err.ToString());  

    }  

    //为标记数组赋值  

    newContent[0] = txtTitle.Text;//标题  

    newContent[1] = "BackColor='#cccfff'";//背景色  

    newContent[2] = "#ff0000";//字体颜色  

    newContent[3] = "100px";//字体大小  

    newContent[4] = txtContent.Text;//主要内容  

    //根据上面新的内容生成html文件  

    try  

    {  

      //指定要生成的HTML文件  

      string fname = Server.MapPath("createHTML") +"\\" + DateTime.Now.ToString("yyyymmddhhmmss") + ".html";  

      //替换html模版文件里的标记为新的内容  

      for(int i=0;i < 5;i++)  

      {  

        strhtml.Replace("$htmlkey["+i+"]",newContent[i]);  

      }  

      //创建文件信息对象  

      FileInfo finfo = new FileInfo(fname);  

      //以打开或者写入的形式创建文件流  

      using(FileStream fs = finfo.OpenWrite())  

      {  

        //根据上面创建的文件流创建写数据流  

        StreamWriter sw = new StreamWriter(fs,System.Text.Encoding.GetEncoding("GB2312"));  

      //把新的内容写到创建的HTML页面中  

      sw.WriteLine(strhtml);  

      sw.Flush();  

      sw.Close();  

    }  

      //设置超级链接的属性  

      hyCreateFile.Text = DateTime.Now.ToString("yyyymmddhhmmss")+".html";  

      hyCreateFile.NavigateUrl = "createHTML/"+DateTime.Now.ToString("yyyymmddhhmmss")+".html";  

    }  

    catch(Exception err)  

    {   

      Response.Write (err.ToString());  

    }  

  }  

CreateDirectory方法的使用  

   using System;   

   using System.IO;  

   class Test   

   {   

     public static void Main()   

     {   

       // Specify the directory you want to manipulate.   

       string path = @"c:\MyDir";  

       try   

       {   

         // Determine whether the directory exists.   

         if (Directory.Exists(path))   

         {   

           Console.WriteLine("That path exists already.");   

           return;   

         }  

         // Try to create the directory.   

         DirectoryInfo di = Directory.CreateDirectory(path);   

         Console.WriteLine("The directory was created successfully at {0}.",   Directory.GetCreationTime(path));  

         // Delete the directory.   

         di.Delete();   

         Console.WriteLine("The directory was deleted successfully.");   

       }   

       catch (Exception e)   

       {   

         Console.WriteLine("The process failed: {0}", e.ToString());   

       }   

       finally {}   

     }   

   }

玩家留言 跟帖评论
编辑推荐
相关文章
同类下载
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 62
  63. 63
  64. 64
  65. 65
  66. 66
  67. 67
  68. 68
  69. 69
  70. 70
  71. 71
  72. 72
  73. 73
  74. 74
  75. 75
  76. 76
  77. 77
  78. 78
  79. 79
  80. 80
  81. 81
  82. 82
  83. 83
  84. 84
  85. 85
  86. 86
  87. 87
  88. 88
  89. 89
  90. 90
  91. 91
  92. 92
  93. 93
  94. 94
  95. 95
  96. 96
  97. 97
  98. 98
  99. 99
  100. 100
  101. 101
  102. 102
  103. 103
  104. 104
  105. 105
  106. 106
  107. 107
  108. 108
  109. 109
  110. 110
  111. 111
  112. 112
  113. 113
  114. 114
  115. 115
  116. 116
  117. 117
  118. 118
  119. 119
  120. 120
  121. 121
  122. 122
  123. 123
  124. 124
  125. 125
  126. 126
  127. 127
  128. 128
  129. 129
  130. 130
  131. 131
  132. 132
  133. 133
  134. 134
  135. 135
  136. 136
  137. 137
  138. 138
  139. 139
  140. 140
  141. 141
  142. 142
  143. 143
  144. 144
  145. 145
  146. 146
  147. 147
  148. 148
  149. 149
  150. 150
  151. 151
  152. 152
  153. 153
  154. 154
  155. 155
  156. 156
  157. 157
  158. 158
  159. 159
  160. 160
  161. 161
  162. 162
  163. 163
  164. 164
  165. 165
  166. 166
  167. 167
  168. 168
  169. 169
  170. 170
  171. 171
  172. 172
  173. 173
  174. 174
  175. 175
  176. 176
  177. 177
  178. 178
  179. 179
  180. 180
  181. 181
  182. 182
  183. 183
  184. 184
  185. 185
  186. 186
  187. 187
  188. 188
  189. 189
  190. 190
  191. 191
  192. 192
  193. 193
  194. 194
  195. 195
  196. 196
  197. 197
  198. 198
  199. 199
  200. 200
  201. 201
  202. 202
  203. 203
  204. 204
  205. 205
  206. 206
  207. 207
  208. 208
  209. 209
  210. 210
  211. 211
  212. 212
  213. 213
  214. 214
  215. 215
  216. 216
  217. 217
  218. 218
  219. 219
  220. 220
  221. 221
  222. 222
  223. 223
  224. 224
  225. 225
  226. 226
  227. 227
  228. 228
  229. 229
  230. 230
  231. 231
  232. 232
  233. 233
  234. 234
  235. 235
  236. 236
  237. 237
  238. 238
  239. 239
  240. 240
  241. 241
  242. 242
  243. 243
  244. 244
  245. 245
  246. 246
  247. 247
  248. 248
  249. 249
  250. 250
  251. 251
  252. 252
  253. 253
  254. 254
  255. 255
  256. 256
  257. 257
  258. 258
  259. 259
  260. 260
  261. 261
  262. 262
  263. 263
  264. 264
  265. 265
  266. 266
  267. 267
  268. 268
  269. 269
  270. 270
  271. 271
  272. 272
  273. 273
  274. 274
  275. 275
  276. 276
  277. 277
  278. 278
  279. 279
  280. 280
  281. 281
  282. 282
  283. 283
  284. 284
  285. 285
  286. 286
  287. 287
  288. 288
  289. 289
  290. 290
  291. 291
  292. 292
  293. 293
  294. 294
  295. 295
  296. 296
  297. 297
  298. 298
  299. 299
  300. 300
  301. 301
  302. 302
  303. 303
  304. 304
  305. 305
  306. 306
  307. 307
  308. 308
  309. 309
  310. 310
  311. 311
  312. 312
  313. 313
  314. 314
  315. 315
  316. 316
  317. 317
  318. 318
  319. 319
  320. 320
  321. 321
  322. 322
  323. 323
  324. 324
  325. 325
  326. 326
  327. 327
  328. 328
  329. 329
  330. 330
  331. 331
  332. 332
  333. 333
  334. 334
  335. 335
  336. 336
  337. 337
  338. 338
  339. 339
  340. 340
  341. 341
  342. 342
  343. 343
  344. 344
  345. 345
  346. 346
  347. 347
  348. 348
  349. 349
  350. 350
  351. 351
  352. 352
  353. 353
  354. 354
  355. 355
  356. 356
  357. 357
  358. 358
  359. 359
  360. 360
  361. 361
  362. 362
  363. 363
  364. 364
  365. 365
  366. 366
  367. 367
  368. 368
  369. 369
  370. 370
  371. 371
  372. 372
  373. 373
  374. 374
  375. 375
  376. 376
  377. 377
  378. 378
  379. 379
  380. 380
  381. 381
  382. 382
  383. 383
  384. 384
  385. 385
  386. 386
  387. 387
  388. 388
  389. 389
  390. 390
  391. 391
  392. 392
  393. 393
  394. 394
  395. 395
  396. 396
  397. 397
  398. 398
  399. 399
  400. 400
  401. 401
  402. 402
  403. 403
  404. 404
  405. 405
  406. 406
  407. 407
  408. 408
  409. 409
  410. 410
  411. 411
  412. 412
  413. 413
  414. 414
  415. 415
  416. 416
  417. 417
  418. 418
  419. 419
  420. 420
  421. 421
  422. 422
  423. 423
  424. 424
  425. 425
  426. 426
  427. 427
  428. 428
  429. 429
  430. 430
  431. 431
  432. 432
  433. 433
  434. 434
  435. 435
  436. 436
  437. 437
  438. 438
  439. 439
  440. 440
  441. 441
  442. 442
  443. 443
  444. 444
  445. 445
  446. 446
  447. 447
  448. 448
  449. 449
  450. 450
  451. 451
  452. 452
  453. 453
  454. 454
  455. 455
  456. 456
  457. 457
  458. 458
  459. 459
  460. 460
  461. 461
  462. 462
  463. 463
  464. 464
  465. 465
  466. 466
  467. 467
  468. 468
  469. 469
  470. 470
  471. 471
  472. 472
  473. 473
  474. 474
  475. 475
  476. 476
  477. 477
  478. 478
  479. 479
  480. 480
  481. 481
  482. 482
  483. 483
  484. 484
  485. 485
  486. 486
  487. 487
  488. 488
  489. 489
  490. 490
  491. 491
  492. 492
  493. 493
  494. 494
  495. 495
  496. 496
  497. 497
  498. 498
  499. 499
  500. 500
  501. 501
  502. 502
  503. 503
  504. 504
  505. 505
  506. 506
  507. 507
  508. 508
  509. 509
  510. 510
  511. 511
  512. 512
  513. 513
  514. 514
  515. 515
  516. 516
  517. 517
  518. 518
  519. 519
  520. 520
  521. 521
/ 521