天天看點

檔案操作類2

using System;

using System.Text;

using System.Web;

using System.IO;

namespace DotNet.Utilities

{

    public class FileOperate

    {

        #region 寫檔案

        protected void Write_Txt(string FileName, string Content)

        {

            Encoding code = Encoding.GetEncoding("gb2312");

            string htmlfilename = HttpContext.Current.Server.MapPath("Precious\\" + FileName + ".txt"); //儲存檔案的路徑

            string str = Content;

            StreamWriter sw = null;

            {

                try

                {

                    sw = new StreamWriter(htmlfilename, false, code);

                    sw.Write(str);

                    sw.Flush();

                }

                catch { }

            }

            sw.Close();

            sw.Dispose();

        }

        #endregion

        #region 讀檔案

        protected string Read_Txt(string filename)

            string temp = HttpContext.Current.Server.MapPath("Precious\\" + filename + ".txt");

            string str = "";

            if (File.Exists(temp))

                StreamReader sr = null;

                    sr = new StreamReader(temp, code);

                    str = sr.ReadToEnd(); // 讀取檔案

                sr.Close();

                sr.Dispose();

            else

                str = "";

            return str;

        #region 取得檔案字尾名

        /****************************************

         * 函數名稱:GetPostfixStr

         * 功能說明:取得檔案字尾名

         * 參    數:filename:檔案名稱

         * 調用示列:

         *           string filename = "aaa.aspx";       

         *           string s = DotNet.Utilities.FileOperate.GetPostfixStr(filename);        

        *****************************************/

        /// <summary>

        /// 取字尾名

        /// </summary>

        /// <param name="filename">檔案名</param>

        /// <returns>.gif|.html格式</returns>

        public static string GetPostfixStr(string filename)

            int start = filename.LastIndexOf(".");

            int length = filename.Length;

            string postfix = filename.Substring(start, length - start);

            return postfix;

         * 函數名稱:WriteFile

         * 功能說明:當檔案不存時,則建立檔案,并追加檔案

         * 參    數:Path:檔案路徑,Strings:文本内容

         *           string Path = Server.MapPath("Default2.aspx");      

         *           string Strings = "這是我寫的内容啊";

         *           DotNet.Utilities.FileOperate.WriteFile(Path,Strings);

        /// 寫檔案

        /// <param name="Path">檔案路徑</param>

        /// <param name="Strings">檔案内容</param>

        public static void WriteFile(string Path, string Strings)

            if (!System.IO.File.Exists(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();

         * 函數名稱:ReadFile

         * 功能說明:讀取文本内容

         * 參    數:Path:檔案路徑

         *           string s = DotNet.Utilities.FileOperate.ReadFile(Path);

        /// 讀檔案

        /// <returns></returns>

        public static string ReadFile(string Path)

            string s = "";

                s = "不存在相應的目錄";

                StreamReader f2 = new StreamReader(Path, System.Text.Encoding.GetEncoding("gb2312"));

                s = f2.ReadToEnd();

                f2.Close();

                f2.Dispose();

            return s;

        #region 追加檔案

         * 函數名稱:FileAdd

         * 功能說明:追加檔案内容

         * 參    數:Path:檔案路徑,strings:内容

         *           string Path = Server.MapPath("Default2.aspx");    

         *           string Strings = "新追加内容";

         *           DotNet.Utilities.FileOperate.FileAdd(Path, Strings);

        /// 追加檔案

        /// <param name="strings">内容</param>

        public static void FileAdd(string Path, string strings)

            StreamWriter sw = File.AppendText(Path);

            sw.Write(strings);

            sw.Flush();

        #region 拷貝檔案

         * 函數名稱:FileCoppy

         * 功能說明:拷貝檔案

         * 參    數:OrignFile:原始檔案,NewFile:新檔案路徑

         *           string OrignFile = Server.MapPath("Default2.aspx");    

         *           string NewFile = Server.MapPath("Default3.aspx");

         *           DotNet.Utilities.FileOperate.FileCoppy(OrignFile, NewFile);

        /// 拷貝檔案

        /// <param name="OrignFile">原始檔案</param>

        /// <param name="NewFile">新檔案路徑</param>

        public static void FileCoppy(string OrignFile, string NewFile)

            File.Copy(OrignFile, NewFile, true);

        #region 删除檔案

         * 函數名稱:FileDel

         * 功能說明:删除檔案

         *           string Path = Server.MapPath("Default3.aspx");   

         *           DotNet.Utilities.FileOperate.FileDel(Path);

        /// 删除檔案

        /// <param name="Path">路徑</param>

        public static void FileDel(string Path)

            File.Delete(Path);

        #region 移動檔案

         * 函數名稱:FileMove

         * 功能說明:移動檔案

         * 參    數:OrignFile:原始路徑,NewFile:新檔案路徑

         *            string OrignFile = Server.MapPath("../說明.txt");   

         *            string NewFile = Server.MapPath("../../說明.txt");

         *            DotNet.Utilities.FileOperate.FileMove(OrignFile, NewFile);

        /// 移動檔案

        /// <param name="OrignFile">原始路徑</param>

        /// <param name="NewFile">新路徑</param>

        public static void FileMove(string OrignFile, string NewFile)

            File.Move(OrignFile, NewFile);

        #region 在目前目錄下建立目錄

         * 函數名稱:FolderCreate

         * 功能說明:在目前目錄下建立目錄

         * 參    數:OrignFolder:目前目錄,NewFloder:新目錄

         *           string OrignFolder = Server.MapPath("test/");   

         *           string NewFloder = "new";

         *           DotNet.Utilities.FileOperate.FolderCreate(OrignFolder, NewFloder);

        /// 在目前目錄下建立目錄

        /// <param name="OrignFolder">目前目錄</param>

        /// <param name="NewFloder">新目錄</param>

        public static void FolderCreate(string OrignFolder, string NewFloder)

            Directory.SetCurrentDirectory(OrignFolder);

            Directory.CreateDirectory(NewFloder);

        /// 建立檔案夾

        /// <param name="Path"></param>

        public static void FolderCreate(string Path)

            // 判斷目标目錄是否存在如果不存在則建立之

            if (!Directory.Exists(Path))

                Directory.CreateDirectory(Path);

        #region 建立目錄

        public static void FileCreate(string Path)

            FileInfo CreateFile = new FileInfo(Path); //建立檔案

            if (!CreateFile.Exists)

                FileStream FS = CreateFile.Create();

                FS.Close();

        #region 遞歸删除檔案夾目錄及檔案

         * 函數名稱:DeleteFolder

         * 功能說明:遞歸删除檔案夾目錄及檔案

         * 參    數:dir:檔案夾路徑

         *           string dir = Server.MapPath("test/"); 

         *           DotNet.Utilities.FileOperate.DeleteFolder(dir);      

        /// 遞歸删除檔案夾目錄及檔案

        /// <param name="dir"></param> 

        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); //删除已空檔案夾                

        #region 将指定檔案夾下面的所有内容copy到目标檔案夾下面 果目标檔案夾為隻讀屬性就會報錯。

         * 函數名稱:CopyDir

         * 功能說明:将指定檔案夾下面的所有内容copy到目标檔案夾下面 果目标檔案夾為隻讀屬性就會報錯。

         * 參    數:srcPath:原始路徑,aimPath:目标檔案夾

         *           string srcPath = Server.MapPath("test/"); 

         *           string aimPath = Server.MapPath("test1/");

         *           DotNet.Utilities.FileOperate.CopyDir(srcPath,aimPath);  

        /// 指定檔案夾下面的所有内容copy到目标檔案夾下面

        /// <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檔案

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

            catch (Exception ee)

                throw new Exception(ee.ToString());

        #region 擷取指定檔案夾下所有子目錄及檔案(樹形)

         * 函數名稱:GetFoldAll(string Path)

         * 功能說明:擷取指定檔案夾下所有子目錄及檔案(樹形)

         * 參    數:Path:詳細路徑

         *           string strDirlist = Server.MapPath("templates");      

         *           this.Literal1.Text = DotNet.Utilities.FileOperate.GetFoldAll(strDirlist); 

        /// 擷取指定檔案夾下所有子目錄及檔案

        /// <param name="Path">詳細路徑</param>

        public static string GetFoldAll(string Path)

            DirectoryInfo thisOne = new DirectoryInfo(Path);

            str = ListTreeShow(thisOne, 0, str);

        /// 擷取指定檔案夾下所有子目錄及檔案函數

        /// <param name="theDir">指定目錄</param>

        /// <param name="nLevel">預設起始值,調用時,一般為0</param>

        /// <param name="Rn">用于疊加的傳入值,一般為空</param>

        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 += "│ ";

                    }

                    Rn += _s + "├";

                Rn += "<b>" + dirinfo.Name.ToString() + "</b><br />";

                FileInfo[] fileInfo = dirinfo.GetFiles();   //目錄下的檔案

                foreach (FileInfo fInfo in fileInfo)

                    if (nLevel == 0)

                        Rn += "│ ├";

                        string _f = "";

                        for (int i = 1; i <= nLevel; i++)

                        {

                            _f += "│ ";

                        }

                        Rn += _f + "│ ├";

                    Rn += fInfo.Name.ToString() + " <br />";

                Rn = ListTreeShow(dirinfo, nLevel + 1, Rn);

            return Rn;

         * 功能說明:擷取指定檔案夾下所有子目錄及檔案(下拉框形)

         *            string strDirlist = Server.MapPath("templates");     

         *            this.Literal2.Text = DotNet.Utilities.FileOperate.GetFoldAll(strDirlist,"tpl","");

        /// 擷取指定檔案夾下所有子目錄及檔案(下拉框形)

        ///<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>";

            str = ListTreeShow(thisOne, 0, str, tplPath);

            return strDrop + str + "</select>";

        /// <param name="tplPath">預設選擇模闆名稱</param>

        public static string ListTreeShow(DirectoryInfo theDir, int nLevel, string Rn, string tplPath)//遞歸目錄 檔案

                Rn += "<option value=\"" + dirinfo.Name.ToString() + "\"";

                if (tplPath.ToLower() == dirinfo.Name.ToString().ToLower())

                    Rn += " selected ";

                Rn += ">";

                    Rn += "┣";

                    Rn += _s + "┣";

                Rn += "" + dirinfo.Name.ToString() + "</option>";

                    Rn += "<option value=\"" + dirinfo.Name.ToString() + "/" + fInfo.Name.ToString() + "\"";

                    if (tplPath.ToLower() == fInfo.Name.ToString().ToLower())

                        Rn += " selected ";

                    Rn += ">";

                    Rn += fInfo.Name.ToString() + "</option>";

                Rn = ListTreeShow(dirinfo, nLevel + 1, Rn, tplPath);

        #region 擷取檔案夾大小

         * 函數名稱:GetDirectoryLength(string dirPath)

         * 功能說明:擷取檔案夾大小

         * 參    數:dirPath:檔案夾詳細路徑

         *           string Path = Server.MapPath("templates");

         *           Response.Write(DotNet.Utilities.FileOperate.GetDirectoryLength(Path));      

        /// 擷取檔案夾大小

        /// <param name="dirPath">檔案夾路徑</param>

        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[i].FullName);

            return len;

        #region 擷取指定檔案詳細屬性

         * 函數名稱:GetFileAttibe(string filePath)

         * 功能說明:擷取指定檔案詳細屬性

         * 參    數:filePath:檔案詳細路徑

         *           string file = Server.MapPath("robots.txt"); 

         *            Response.Write(DotNet.Utilities.FileOperate.GetFileAttibe(file));        

        /// 擷取指定檔案詳細屬性

        /// <param name="filePath">檔案詳細路徑</param>

        public static string GetFileAttibe(string filePath)

            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;

    }

}

上一篇: C# NetHelper
下一篇: jsHelper