程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> 關於.NET >> C#常用的IO操作方法,

C#常用的IO操作方法,

編輯:關於.NET

C#常用的IO操作方法,


public class IoHelper
    {
        /// <summary>
        /// 判斷文件是否存在
        /// </summary>
        /// <param name="fileName">文件路徑</param>
        /// <returns>是否存在</returns>
        public static bool Exists(string fileName)
        {
            if (fileName == null || fileName.Trim() == "")
            {
                return false;
            }
            return File.Exists(fileName);
        }


        /// <summary>
        /// 創建文件夾
        /// </summary>
        /// <param name="dirName">文件夾名</param>
        /// <returns></returns>
        public static bool CreateDir(string dirName)
        {
            try
            {
                if (dirName == null)
                    throw new Exception("dirName");
                if (!Directory.Exists(dirName))
                {
                    Directory.CreateDirectory(dirName);
                }
                return true;
            }
            catch (Exception er)
            {
                throw new Exception(er.Message);
            }
        }


        /// <summary>
        /// 創建文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <returns>創建失敗返回false</returns>
        public static bool CreateFile(string fileName)
        {
            try
            {
                if (File.Exists(fileName)) return false;
                var fs = File.Create(fileName);
                fs.Close();
                fs.Dispose();
            }
            catch (IOException ioe)
            {
                throw new IOException(ioe.Message);
            }

            return true;
        }


        /// <summary>
        /// 讀文件內容,轉化為字符類型
        /// </summary>
        /// <param name="fileName">文件路徑</param>
        /// <returns></returns>
        public static string Read(string fileName)
        {
            if (!Exists(fileName))
            {
                return null;
            }
            //將文件信息讀入流中
            using (var fs = new FileStream(fileName, FileMode.Open))
            {
                return new StreamReader(fs).ReadToEnd();
            }
        }


        /// <summary>
        /// 文件轉化為Char[]數組
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static char[] FileRead(string fileName)
        {
            if (!Exists(fileName))
            {
                return null;
            }
            var byData = new byte[1024];
            var charData = new char[1024];
            try
            {
                var fileStream = new FileStream(fileName, FileMode.Open);
                fileStream.Seek(135, SeekOrigin.Begin);
                fileStream.Read(byData, 0, 1024);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            var decoder = Encoding.UTF8.GetDecoder();
            decoder.GetChars(byData, 0, byData.Length, charData, 0);
            return charData;
        }



        /// <summary>
        /// 文件轉化為byte[]
        /// </summary>
        /// <param name="fileName">文件路徑</param>
        /// <returns></returns>
        public static byte[] ReadFile(string fileName)
        {
            FileStream pFileStream = null;
            try
            {
                pFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                var r = new BinaryReader(pFileStream);
                //將文件指針設置到文件開
                r.BaseStream.Seek(0, SeekOrigin.Begin);
                var pReadByte = r.ReadBytes((int)r.BaseStream.Length);
                return pReadByte;
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);

            }
            finally
            {
                if (pFileStream != null) pFileStream.Close();
            }
        }


        /// <summary>
        /// 將byte寫入文件
        /// </summary>
        /// <param name="pReadByte">字節流</param>
        /// <param name="fileName">文件路徑</param>
        /// <returns></returns>
        public static bool WriteFile(byte[] pReadByte, string fileName)
        {
            FileStream pFileStream = null;
            try
            {
                pFileStream = new FileStream(fileName, FileMode.OpenOrCreate);
                pFileStream.Write(pReadByte, 0, pReadByte.Length);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
            finally
            {
                if (pFileStream != null) pFileStream.Close();
            }
            return true;

        }

        public static string ReadLine(string fileName)
        {
            if (!Exists(fileName))
            {
                return null;
            }
            using (var fs = new FileStream(fileName, FileMode.Open))
            {
                return new StreamReader(fs).ReadLine();
            }
        }


        /// <summary>
        /// 寫文件
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="content">文件內容</param>
        /// <returns></returns>
        public static bool Write(string fileName, string content)
        {
            if (Exists(fileName) || content == null)
            {
                return false;
            }
            try
            {
                //將文件信息讀入流中
                //初始化System.IO.FileStream類的新實例與指定路徑和創建模式
                using (var fs = new FileStream(fileName, FileMode.OpenOrCreate))
                {
                    //鎖住流
                    lock (fs)
                    {
                        if (!fs.CanWrite)
                        {
                            throw new System.Security.SecurityException("文件fileName=" + fileName + "是只讀文件不能寫入!");
                        }

                        var buffer = Encoding.Default.GetBytes(content);
                        fs.Write(buffer, 0, buffer.Length);
                        return true;
                    }
                }
            }
            catch (IOException ioe)
            {
                throw new Exception(ioe.Message);
            }

        }


        /// <summary>
        /// 寫入一行
        /// </summary>
        /// <param name="fileName">文件名</param>
        /// <param name="content">內容</param>
        /// <returns></returns>
        public static bool WriteLine(string fileName, string content)
        {
            if (string.IsNullOrEmpty(fileName))
                throw new ArgumentNullException(fileName);
            if (string.IsNullOrEmpty(content))
                throw new ArgumentNullException(content);
            using (var fs = new FileStream(fileName, FileMode.OpenOrCreate | FileMode.Append))
            {
                //鎖住流
                lock (fs)
                {
                    if (!fs.CanWrite)
                    {
                        throw new System.Security.SecurityException("文件fileName=" + fileName + "是只讀文件不能寫入!");
                    }

                    var sw = new StreamWriter(fs);
                    sw.WriteLine(content);
                    sw.Dispose();
                    sw.Close();
                    return true;
                }
            }
        }


        /// <summary>
        /// 復制目錄
        /// </summary>
        /// <param name="fromDir">被復制的目錄</param>
        /// <param name="toDir">復制到的目錄</param>
        /// <returns></returns>
        public static bool CopyDir(DirectoryInfo fromDir, string toDir)
        {
            return CopyDir(fromDir, toDir, fromDir.FullName);
        }


        /// <summary>
        /// 復制目錄
        /// </summary>
        /// <param name="fromDir">被復制的目錄</param>
        /// <param name="toDir">復制到的目錄</param>
        /// <returns></returns>
        public static bool CopyDir(string fromDir, string toDir)
        {
            if (fromDir == null || toDir == null)
            {
                throw new NullReferenceException("參數為空");
            }

            if (fromDir == toDir)
            {
                throw new Exception("兩個目錄都是" + fromDir);
            }

            if (!Directory.Exists(fromDir))
            {
                throw new IOException("目錄fromDir=" + fromDir + "不存在");
            }

            var dir = new DirectoryInfo(fromDir);
            return CopyDir(dir, toDir, dir.FullName);
        }


        /// <summary>
        /// 復制目錄
        /// </summary>
        /// <param name="fromDir">被復制的目錄</param>
        /// <param name="toDir">復制到的目錄</param>
        /// <param name="rootDir">被復制的根目錄</param>
        /// <returns></returns>
        private static bool CopyDir(DirectoryInfo fromDir, string toDir, string rootDir)
        {
            foreach (var f in fromDir.GetFiles())
            {
                var filePath = toDir + f.FullName.Substring(rootDir.Length);
                var newDir = filePath.Substring(0, filePath.LastIndexOf("\\", StringComparison.Ordinal));
                CreateDir(newDir);
                File.Copy(f.FullName, filePath, true);
            }

            foreach (var dir in fromDir.GetDirectories())
            {
                CopyDir(dir, toDir, rootDir);
            }

            return true;
        }


        /// <summary>
        /// 刪除文件
        /// </summary>
        /// <param name="fileName">文件的完整路徑</param>
        /// <returns></returns>
        public static bool DeleteFile(string fileName)
        {
            try
            {
                if (!Exists(fileName)) return false;
                File.Delete(fileName);
            }
            catch (IOException ioe)
            {
                throw new ArgumentNullException(ioe.Message);
            }

            return true;
        }


        public static void DeleteDir(DirectoryInfo dir)
        {
            if (dir == null)
            {
                throw new NullReferenceException("目錄不存在");
            }

            foreach (var d in dir.GetDirectories())
            {
                DeleteDir(d);
            }

            foreach (var f in dir.GetFiles())
            {
                DeleteFile(f.FullName);
            }

            dir.Delete();

        }


        /// <summary>
        /// 刪除目錄
        /// </summary>
        /// <param name="dir">指定目錄</param>
        /// <param name="onlyDir">是否只刪除目錄</param>
        /// <returns></returns>
        public static bool DeleteDir(string dir, bool onlyDir)
        {
            if (dir == null || dir.Trim() == "")
            {
                throw new NullReferenceException("目錄dir=" + dir + "不存在");
            }

            if (!Directory.Exists(dir))
            {
                return false;
            }

            var dirInfo = new DirectoryInfo(dir);
            if (dirInfo.GetFiles().Length == 0 && dirInfo.GetDirectories().Length == 0)
            {
                Directory.Delete(dir);
                return true;
            }


            if (!onlyDir)
            {
                return false;
            }
            DeleteDir(dirInfo);
            return true;
        }


        /// <summary>
        /// 在指定的目錄中查找文件
        /// </summary>
        /// <param name="dir">目錄</param>
        /// <param name="fileName">文件名</param>
        /// <returns></returns>
        public static bool FindFile(string dir, string fileName)
        {
            if (dir == null || dir.Trim() == "" || fileName == null || fileName.Trim() == "" || !Directory.Exists(dir))
            {
                return false;
            }

            //傳入文件路徑,獲取當前文件對象
            var dirInfo = new DirectoryInfo(dir);
            return FindFile(dirInfo, fileName);

        }


        /// <summary>
        /// 返回文件是否存在
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static bool FindFile(DirectoryInfo dir, string fileName)
        {
            foreach (var d in dir.GetDirectories())
            {
                if (File.Exists(d.FullName + "\\" + fileName))
                {
                    return true;
                }
                FindFile(d, fileName);
            }

            return false;
        }


        /// <summary>
        /// 獲取指定文件夾中的所有文件夾名稱
        /// </summary>
        /// <param name="folderPath">路徑</param>
        /// <returns></returns>
        public static List<string> FolderName(string folderPath)
        {
            var listFolderName = new List<string>();
            try
            {
                var info = new DirectoryInfo(folderPath);

                listFolderName.AddRange(info.GetDirectories().Select(nextFolder => nextFolder.Name));
            }
            catch (Exception er)
            {
                throw new Exception(er.Message);
            }

            return listFolderName;

        }


        /// <summary>
        /// 獲取指定文件夾中的文件名稱
        /// </summary>
        /// <param name="folderPath">路徑</param>
        /// <returns></returns>
        public static List<string> FileName(string folderPath)
        {
            var listFileName = new List<string>();
            try
            {
                var info = new DirectoryInfo(folderPath);

                listFileName.AddRange(info.GetFiles().Select(nextFile => nextFile.Name));
            }
            catch (Exception er)
            {
                throw new Exception(er.Message);
            }

            return listFileName;
        }
    }

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved