c# 文件操作類庫


以下代碼從網上搜集整理:

 

public class FileOperate
    {

        #region 刪除文件
        /// <summary>
        /// 刪除文件
        /// </summary>
        /// <param name="FileFullPath">文件的全路徑.</param>
        /// <returns>bool</returns>
        public static bool DeleteFile(string FileFullPath)
        {
            if (File.Exists(FileFullPath) == true) //用靜態類判斷文件是否存在
            {
                File.SetAttributes(FileFullPath, FileAttributes.Normal); //設置文件的屬性為正常(如果文件為只讀的話直接刪除會報錯)
                File.Delete(FileFullPath); //刪除文件
                return true;
            }
            else //文件不存在
            {
                return false;
            }
        }
        #endregion

        #region 獲取文件名(包含擴展名)
        /// <summary>
        /// 獲取文件名(包含擴展名)
        /// </summary>
        /// <param name="FileFullPath">文件全路徑</param>
        /// <returns>string</returns>
        public static string GetFileName(string FileFullPath)
        {
            if (File.Exists(FileFullPath) == true)
            {
                FileInfo F = new FileInfo(FileFullPath); //FileInfo類為提供創建、復制、刪除等方法
                return F.Name; //獲取文件名(包含擴展名)
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 獲取文件文件擴展名
        /// <summary>
        /// 獲取文件文件擴展名
        /// </summary>
        /// <param name="FileFullPath">文件全路徑</param>
        /// <returns>string</returns>
        public static string GetFileExtension(string FileFullPath)
        {
            if (File.Exists(FileFullPath) == true)
            {
                FileInfo F = new FileInfo(FileFullPath);
                return F.Extension; //獲取文件擴展名(包含".",如:".mp3")
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 獲取文件名(可包含擴展名)
        /// <summary>
        /// 獲取文件名(可包含擴展名)
        /// </summary>
        /// <param name="FileFullPath">文件全路徑</param>
        /// <param name="IncludeExtension">是否包含擴展名</param>
        /// <returns>string</returns>
        public static string GetFileName(string FileFullPath, bool IncludeExtension)
        {
            if (File.Exists(FileFullPath) == true)
            {
                FileInfo F = new FileInfo(FileFullPath);
                if (IncludeExtension)
                {
                    return F.Name;   //返回文件名(包含擴展名)
                }
                else
                {
                    return F.Name.Replace(F.Extension, ""); //把擴展名替換為空字符
                }
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 外部打開文件
        /// <summary>
        /// 根據傳來的文件全路徑,外部打開文件,默認用系統注冊類型關聯軟件打開
        /// </summary>
        /// <param name="FileFullPath">文件的全路徑</param>
        /// <returns>bool</returns>
        public static bool OpenFile(string FileFullPath)
        {
            if (File.Exists(FileFullPath) == true)
            {
                System.Diagnostics.Process.Start(FileFullPath); //打開文件,默認用系統注冊類型關聯軟件打開
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 獲取文件大小
        /// <summary>
        /// 獲取文件大小
        /// </summary>
        /// <param name="FileFullPath">文件全路徑</param>
        /// <returns>string</returns>
        public static string GetFileSize(string FileFullPath)
        {
            if (File.Exists(FileFullPath) == true)
            {
                FileInfo F = new FileInfo(FileFullPath);
                long FL = F.Length;
                if (FL > (1024 * 1024 * 1024)) //由大向小來判斷文件的大小
                {
                    return Math.Round((FL + 0.00) / (1024 * 1024 * 1024), 2).ToString() + " GB"; //將雙精度浮點數舍入到指定的小數(long類型與double類型運算,結果會是一個double類型)
                }
                else if (FL > (1024 * 1024))
                {
                    return Math.Round((FL + 0.00) / (1024 * 1024), 2).ToString() + " MB";
                }
                else if (FL > 1024)
                {
                    return Math.Round((FL + 0.00) / 1024, 2).ToString() + " KB";
                }
                else
                {
                    return FL.ToString();
                }
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 文件轉換成二進制
        /// <summary>
        /// 文件轉換成二進制,返回二進制數組Byte[]
        /// </summary>
        /// <param name="FileFullPath">文件全路徑</param>
        /// <returns>byte[] 包含文件流的二進制數組</returns>
        public static byte[] FileToStreamByte(string FileFullPath)
        {
            if (File.Exists(FileFullPath) == true)
            {
                FileStream FS = new FileStream(FileFullPath, FileMode.Open); //創建一個文件流
                byte[] fileData = new byte[FS.Length];                       //創建一個字節數組,用於保存流
                FS.Read(fileData, 0, fileData.Length);                       //從流中讀取字節塊,保存到緩存中
                FS.Close();                                                  //關閉流(一定得關閉,否則流一直存在)
                return fileData;                                             //返回字節數組
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 二進制生成文件
        /// <summary>
        /// 二進制數組Byte[]生成文件
        /// </summary>
        /// <param name="FileFullPath">要生成的文件全路徑</param>
        /// <param name="StreamByte">要生成文件的二進制 Byte 數組</param>
        /// <returns>bool 是否生成成功</returns>
        public static bool ByteStreamToFile(string FileFullPath, byte[] StreamByte)
        {
            try
            {
                if (File.Exists(FileFullPath) == true) //判斷要創建的文件是否存在,若存在則先刪除
                {
                    File.Delete(FileFullPath);
                }
                FileStream FS = new FileStream(FileFullPath, FileMode.OpenOrCreate); //創建文件流(打開或創建的方式)
                FS.Write(StreamByte, 0, StreamByte.Length); //把文件流寫到文件中
                FS.Close();
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region 寫文件
        /// <summary>
        /// 寫文件
        /// </summary>
        /// <param name="Path">文件路徑</param>
        /// <param name="Strings">文件內容</param>
        public static void WriteFile(string FileFullPath, string Strings)
        {
            if (!System.IO.File.Exists(FileFullPath))
            {
                System.IO.FileStream fs = System.IO.File.Create(FileFullPath);
                fs.Close();
            }
            System.IO.StreamWriter sw = new System.IO.StreamWriter(FileFullPath, false, System.Text.Encoding.GetEncoding("gb2312"));
            sw.Write(Strings);
            sw.Flush();
            sw.Close();
            sw.Dispose();
        }
        #endregion

        #region 讀文件
        /// <summary>
        /// 讀文件
        /// </summary>
        /// <param name="Path">文件路徑</param>
        /// <returns></returns>
        public static string ReadFile(string FileFullPath)
        {
            string stemp = "";
            if (!System.IO.File.Exists(FileFullPath))
                stemp = "不存在相應的目錄";
            else
            {
                StreamReader fr = new StreamReader(FileFullPath, System.Text.Encoding.GetEncoding("gb2312"));
                stemp = fr.ReadToEnd();
                fr.Close();
                fr.Dispose();
            }

            return stemp;
        }
        #endregion

        #region 追加文本
        /// <summary>
        /// 追加文本
        /// </summary>
        /// <param name="Path">文件路徑</param>
        /// <param name="strings">內容</param>
        public static void FileAdd(string FileFullPath, string strings)
        {
            StreamWriter sw = File.AppendText(FileFullPath);
            sw.Write(strings);
            sw.Flush();
            sw.Close();
        }
        #endregion

        #region Xml文件序列化
        /// <summary>
        /// 將Xml文件序列化(可起到加密和壓縮XML文件的目的)
        /// </summary>
        /// <param name="FileFullPath">要序列化的XML文件全路徑</param>
        /// <returns>bool 是否序列化成功</returns>
        public static bool SerializeXml(string FileFullPath)   //序列化:
        {
            try
            {
                System.Data.DataSet DS = new System.Data.DataSet(); //創建數據集,用來臨時存儲XML文件
                DS.ReadXml(FileFullPath); //將XML文件讀入到數據集中
                FileStream FS = new FileStream(FileFullPath + ".tmp", FileMode.OpenOrCreate); //創建一個.tmp的臨時文件
                System.Runtime.Serialization.Formatters.Binary.BinaryFormatter FT = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); //使用二進制格式化程序進行序列化
                FT.Serialize(FS, DS); //把數據集序列化后存入文件中
                FS.Close(); //一定要關閉文件流,否則文件改名會報錯(文件正在使用錯誤)
                DeleteFile(FileFullPath); //刪除原XML文件
                File.Move(FileFullPath + ".tmp", FileFullPath); //改名(把臨時文件名改成原來的xml文件名)
                return true;
            }
            catch
            {
                return false;
            }
        }
        #endregion

        #region 反序列化XML文件
        /// <summary>
        /// 反序列化XML文件
        /// </summary>
        /// <param name="FileFullPath">要反序列化XML文件的全路徑</param>
        /// <returns>bool 是否反序列化XML文件</returns>
        public static bool DeSerializeXml(string FileFullPath)
        {
            FileStream FS = new FileStream(FileFullPath, FileMode.Open); //打開XML文件流
            System.Runtime.Serialization.Formatters.Binary.BinaryFormatter FT = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter(); //使用二進制格式化程序進行序列化
            ((System.Data.DataSet)FT.Deserialize(FS)).WriteXml(FileFullPath + ".tmp"); //把文件反序列化后存入.tmp臨時文件中
            FS.Close(); //關閉並釋放流
            DeleteFile(FileFullPath); //刪除原文件
            File.Move(FileFullPath + ".tmp", FileFullPath); //改名(把臨時文件改成原來的xml文件)
            return true;
        }
        #endregion

        #region 壓縮文件
        /// <summary>
        /// 壓縮文件
        /// </summary>
        /// <param name="sourceFile">源文件</param>
        /// <param name="destinationFile">目標文件</param>
        public static void CompressFile(string sourceFile, string destinationFile)
        {
            // 文件是否存在
            if (File.Exists(sourceFile) == false)
            {
                throw new FileNotFoundException();
            }

            byte[] buffer = null;
            FileStream sourceStream = null;
            FileStream destinationStream = null;
            GZipStream compressedStream = null;

            try
            {
                // 讀取源文件到byte數組
                sourceStream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.Read);

                buffer = new byte[sourceStream.Length];
                int checkCounter = sourceStream.Read(buffer, 0, buffer.Length);

                if (checkCounter != buffer.Length)
                {
                    throw new ApplicationException();
                }

                destinationStream = new FileStream(destinationFile, FileMode.OpenOrCreate, FileAccess.Write);

                compressedStream = new GZipStream(destinationStream, CompressionMode.Compress, true);

                compressedStream.Write(buffer, 0, buffer.Length);
            }
            catch (ApplicationException ex)
            {
                throw (ex);
            }
            finally
            {
                if (sourceStream != null)
                    sourceStream.Close();

                if (compressedStream != null)
                    compressedStream.Close();

                if (destinationStream != null)
                    destinationStream.Close();
            }
        }
        #endregion

        #region 解壓文件
        /// <summary>
        /// 解壓文件
        /// </summary>
        /// <param name="sourceFile">源文件</param>
        /// <param name="destinationFile">目標文件</param>
        public static void DeCompressFile(string sourceFile, string destinationFile)
        {
            if (File.Exists(sourceFile) == false)
            {
                throw new FileNotFoundException();
            }

            FileStream sourceStream = null;
            FileStream destinationStream = null;
            GZipStream decompressedStream = null;
            byte[] quartetBuffer = null;

            try
            {
                sourceStream = new FileStream(sourceFile, FileMode.Open);

                decompressedStream = new GZipStream(sourceStream, CompressionMode.Decompress, true);

                quartetBuffer = new byte[4];
                int position = (int)sourceStream.Length - 4;
                sourceStream.Position = position;
                sourceStream.Read(quartetBuffer, 0, 4);
                sourceStream.Position = 0;
                int checkLength = BitConverter.ToInt32(quartetBuffer, 0);

                byte[] buffer = new byte[checkLength + 100];

                int offset = 0;
                int total = 0;

                while (true)
                {
                    int bytesRead = decompressedStream.Read(buffer, offset, 100);

                    if (bytesRead == 0)
                        break;

                    offset += bytesRead;
                    total += bytesRead;
                }

                destinationStream = new FileStream(destinationFile, FileMode.Create);
                destinationStream.Write(buffer, 0, total);

                destinationStream.Flush();
            }
            catch (ApplicationException ex)
            {
                throw (ex);
            }
            finally
            {
                if (sourceStream != null)
                    sourceStream.Close();

                if (decompressedStream != null)
                    decompressedStream.Close();

                if (destinationStream != null)
                    destinationStream.Close();
            }

        }
        #endregion

        #region 保存圖片
        /// <summary>
        /// 保存為Jpg圖片
        /// </summary>
        /// <param name="bsrc">示例:(BitmapSource)Img.Source</param>
        /// <param name="quality">圖片質量(0-100),若不設置,則默認取80</param>
        /// <returns>是否成功</returns>
        static public bool SaveImage2Jpg(BitmapSource bsrc, int quality = -1)
        {
            bool ret = false;

            if (null != bsrc)
            {
                System.Windows.Forms.SaveFileDialog sf = new System.Windows.Forms.SaveFileDialog();
                sf.FileName = "未命名";
                sf.DefaultExt = ".jpg";
                sf.Filter = "jpg (.jpg)|*.jpg";

                if (System.Windows.Forms.DialogResult.OK == sf.ShowDialog())
                {
                    JpegBitmapEncoder encoder = new JpegBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(bsrc));
                    using (Stream stream = File.Create(sf.FileName))
                    {
                        if (quality >= 0 && quality <= 100)
                        {
                            encoder.QualityLevel = quality;
                        }
                        else
                        {
                            encoder.QualityLevel = 80;
                        }
                        try
                        {
                            encoder.Save(stream);
                            ret = true;
                        }
                        catch (System.Exception ex)
                        {
                            
                        }
                    }
                }
            }

            return ret;
        }
        #endregion

        #region 加載圖片
        /// <summary>
        /// 圖片加載
        /// </summary>
        /// <param name="str">路徑</param>
        /// <param name="dpWidth">圖片解析的寬度(應為程序中所定義的imgWidth,如有特殊需要可自定義)</param>
        /// <returns>BitmapImage</returns>
        static public BitmapImage LoadImages(string str, int dpWidth)
        {
            BitmapImage bitmap = new BitmapImage();
            MemoryStream ms = null;
            using (BinaryReader binReader = new BinaryReader(File.Open(str, FileMode.Open, FileAccess.Read, FileShare.Read)))
            {
                try
                {
                    FileInfo fileInfo = new FileInfo(str);
                    byte[] bytes = binReader.ReadBytes((int)fileInfo.Length);

                    bitmap.BeginInit();
                    bitmap.CacheOption = BitmapCacheOption.OnLoad;
                    ms = new MemoryStream(bytes);
                    bitmap.StreamSource = ms;
                    bitmap.DecodePixelWidth = dpWidth;
                    bitmap.EndInit();
                    bitmap.Freeze();
                }
                catch (Exception ep)
                {
                    MessageBox.Show(ep.Message);
                }
                finally
                {
                    if (null != ms)
                    {
                        ms.Dispose();
                        ms = null;
                    }
                    binReader.Close();
                    GC.Collect();
                }
            }
            return bitmap;
        }
        #endregion

        #region 寫日志文件
        /// <summary>
        /// 寫日志文件
        /// </summary>
        /// <param name="path">日志文件路徑</param>
        /// <param name="msg">日志內容</param>
        public static void Log(string path,string msg)
        {
            DateTime dt = System.DateTime.Now;
            msg += "\r\n時間:" + dt.ToString() + " " + dt.Millisecond.ToString() + "------>";
            FileStream fs = new FileStream(path, FileMode.Append);
            try
            {
                //獲得字節數組
                byte[] data = new System.Text.UTF8Encoding().GetBytes(msg);
                //開始寫入
                fs.Write(data, 0, data.Length);
                //清空緩沖區、關閉流
                fs.Flush();
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                if (null != fs)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }
        }
        #endregion

        #region 文件拷貝(可覆蓋)
        /// <summary>
        /// 文件拷貝(可覆蓋)
        /// </summary>
        /// <param name="sourceFile">源文件</param>
        /// <param name="destFile">目標文件</param>
        /// <returns></returns>
        public static bool FileCopy(string sourceFile, string destFile)
        {
            bool ret = false;

            if (File.Exists(sourceFile))
            {
                try
                {
                    if (File.Exists(destFile))
                    {
                        File.Delete(destFile);
                    }
                    File.Copy(sourceFile, destFile);
                    ret = true;
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
                finally
                {
                }
            }

            return ret;
        }
        #endregion
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM