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
    }

 

转载于:https://www.cnblogs.com/zhangjianli/archive/2012/06/01/2530052.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#基础类 1.Chart图形 Assistant创建显示图像的标签和文件 OWCChart统计图的封装类 2.Cookie&Session;&Cache;缓存帮助类 CacheHelper C#操作缓存的帮助类,实现了怎么设置缓存,怎么取缓存,怎么清理缓存等方法,只需要调用方法就可以实现 CookieHelper C#操作Cookie的帮助类,添加Cookie,删除Cookie,修改Cookie,清理Cookie SessionHelper C#关于Session的操作,获取Session,设置Session,删除Session使用方便,只需要调用方法就可以了 SessionHelper2 C#关于Session的一些高级操作,比如取Session对象,取Session数据等等 3.CSV文件转换 CsvHelper CSV文件导入DataTable和DataTable导出到Csv文件操作 4.DEncrypt 加密/解密帮助类 DEncrypt C#DEncrypt加密/DEncrypt解密帮助类 ,多种方式,可以设置Key DESEncrypt C#DESEncrypt加密/DESEncrypt解密帮助类 ,多种方式,可以设置Key Encrypt C#Encrypt--Encrypt加密/Encrypt解密/附加有MD5加密,个人感觉很不错的一个加密类 HashEncode 哈希加密帮助类,得到随机哈希加密字符串,随机哈希数字加密等 MySecurity MySecurity--Security安全加密/Security Base64/Security文件加密,以及一些常用的操作方法 RSACryption RSACryption--RSA加密/RSA解密字符串 RSA加密应用最多是银行接口,这里的方法可以直接使用哦 5.FTP操作类 FTPClient   FTPClient--FTP操作帮助类,FTP上传,FTP下载,FTP文件操作,FTP目录操作 FTPHelper FTPHelper-FTP帮助类,FTP常用操作方法,添加文件,删除文件等 FTPOperater FTP操作帮助类,方法比较多,比较实用 6.JS操作类 JsHelper JsHelper--Javascript操作帮助类,输出各种JS方法,方便不懂JS的人使用,减少代码量 7.JSON 转化类 ConvertJson List转成Json|对象转成Json|集合转成Json|DataSet转成Json|DataTable转成Json|DataReader转成Json等 8.Mime MediaTypes 电子邮件类型帮助类,规定是以Xml,HTML还是文本方式发送邮件 MimeEntity Mime实体帮助类 MimeHeaders mime的Header帮助类 MimeReader mime读取帮助类 QuotedPrintableEncoding mimeEncoding帮助类 9.PDF 转化类 PDFOperation PDFOperation--C#PDF文件操作帮助类 类主要功能有1.构造函数2.私有字段3.设置字体4.设置页面大小 5.实例化文档6.打开文档对象7.关闭打开的文档8.添加段落9.添加图片10.添加链接、点 等功能 10.ResourceManager 操作类 AppMessage app消息格式化类,返加字符串帮助类 ResourceManager C#一个操作Resource的帮助类 ResourceManagerWrapper Resources 操作Resources的帮助类,使用Api的方式 Sample.xml 11.XML操作类 XmlHelper 操作Xml文档的帮助类,主要是添加,删除,修改,查询节点的操作操作后进行保存的功能。 XMLProcess 操作Xml文档的帮助类,主要是添加,删除,修改,查询节点的操作的功能。 12.弹出消息类 MessageBox JS弹出信息帮助类 ShowMessageBox 相对于MessageBox更丰富的提示类 13.导出Excel 操作类 DataToExcel

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值