asp。net中常用的文件操作类

**
文件操作类
**/
#region 引用命名空间
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
#endregion
namespace CommonUtilities
{
    /// <summary>
    /// 文件操作类
    /// </summary>
    public class FileHelper
    {
        #region 检测指定目录是否存在
        /// <summary>
        /// 检测指定目录是否存在
        /// </summary>
        /// <param name="directoryPath">目录的绝对路径</param>        
        public static bool IsExistDirectory( string directoryPath )
        {
            return Directory.Exists( directoryPath );
        }
        #endregion
        #region 检测指定文件是否存在
        /// <summary>
        /// 检测指定文件是否存在,如果存在则返回true。
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>        
        public static bool IsExistFile( string filePath )
        {
            return File.Exists( filePath );            
        }
        #endregion
        #region 检测指定目录是否为空
        /// <summary>
        /// 检测指定目录是否为空
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>        
        public static bool IsEmptyDirectory( string directoryPath )
        {
            try
            {
                //判断是否存在文件
                string[] fileNames = GetFileNames( directoryPath );
                if ( fileNames.Length > 0 )
                {
                    return false;
                }
                //判断是否存在文件夹
                string[] directoryNames = GetDirectories( directoryPath );
                if ( directoryNames.Length > 0 )
                {
                    return false;
                }
                return true;
            }
            catch ( Exception ex )
            {
                LogHelper.WriteTraceLog( TraceLogLevel.Error, ex.Message );
                return true;
            }
        }
        #endregion
        #region 检测指定目录中是否存在指定的文件
        /// <summary>
        /// 检测指定目录中是否存在指定的文件,若要搜索子目录请使用重载方法.
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>
        /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
        /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>        
        public static bool Contains( string directoryPath, string searchPattern )
        {
            try
            {
                //获取指定的文件列表
                string[] fileNames = GetFileNames( directoryPath, searchPattern, false );
                //判断指定文件是否存在
                if ( fileNames.Length == 0 )
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch ( Exception ex )
            {
                LogHelper.WriteTraceLog( TraceLogLevel.Error, ex.Message );
                return false;
            }
        }
        /// <summary>
        /// 检测指定目录中是否存在指定的文件
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>
        /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
        /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param> 
        /// <param name="isSearchChild">是否搜索子目录</param>
        public static bool Contains( string directoryPath, string searchPattern, bool isSearchChild )
        {
            try
            {
                //获取指定的文件列表
                string[] fileNames = GetFileNames( directoryPath, searchPattern, true );
                //判断指定文件是否存在
                if ( fileNames.Length == 0 )
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch ( Exception ex )
            {
                LogHelper.WriteTraceLog( TraceLogLevel.Error, ex.Message );
                return false;
            }
        }
        #endregion       
        #region 创建一个目录
        /// <summary>
        /// 创建一个目录
        /// </summary>
        /// <param name="directoryPath">目录的绝对路径</param>
        public static void CreateDirectory( string directoryPath )
        {
            //如果目录不存在则创建该目录
            if ( !IsExistDirectory( directoryPath ) )
            {
                Directory.CreateDirectory( directoryPath );
            }
        }
        #endregion
        #region 创建一个文件
        /// <summary>
        /// 创建一个文件。
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        public static void CreateFile( string filePath )
        {
            try
            {
                //如果文件不存在则创建该文件
                if ( !IsExistFile( filePath ) )
                {
                    //创建一个FileInfo对象
                    FileInfo file = new FileInfo( filePath );
                    //创建文件
                    FileStream fs = file.Create();
                    //关闭文件流
                    fs.Close();
                }
            }
            catch ( Exception ex )
            {
                LogHelper.WriteTraceLog( TraceLogLevel.Error, ex.Message );
                throw ex;
            }
        }
        /// <summary>
        /// 创建一个文件,并将字节流写入文件。
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        /// <param name="buffer">二进制流数据</param>
        public static void CreateFile( string filePath, byte[] buffer )
        {
            try
            {
                //如果文件不存在则创建该文件
                if ( !IsExistFile( filePath ) )
                {
                    //创建一个FileInfo对象
                    FileInfo file = new FileInfo( filePath );
                    //创建文件
                    FileStream fs = file.Create();
                    //写入二进制流
                    fs.Write( buffer, 0, buffer.Length );
                    //关闭文件流
                    fs.Close();
                }
            }
            catch ( Exception ex )
            {
                LogHelper.WriteTraceLog( TraceLogLevel.Error, ex.Message );
                throw ex;
            }
        }
        #endregion
        #region 获取文本文件的行数
        /// <summary>
        /// 获取文本文件的行数
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>        
        public static int GetLineCount( string filePath )
        {
            //将文本文件的各行读到一个字符串数组中
            string[] rows = File.ReadAllLines( filePath );
            //返回行数
            return rows.Length;
        }
        #endregion
        #region 获取一个文件的长度
        /// <summary>
        /// 获取一个文件的长度,单位为Byte
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>        
        public static int GetFileSize( string filePath )
        {
            //创建一个文件对象
            FileInfo fi = new FileInfo( filePath );
            //获取文件的大小
            return (int)fi.Length;
        }
        /// <summary>
        /// 获取一个文件的长度,单位为KB
        /// </summary>
        /// <param name="filePath">文件的路径</param>        
        public static double GetFileSizeByKB( string filePath )
        {
            //创建一个文件对象
            FileInfo fi = new FileInfo( filePath );           
            //获取文件的大小
            return ConvertHelper.ToDouble( ConvertHelper.ToDouble( fi.Length ) / 1024 , 1 );
        }
        /// <summary>
        /// 获取一个文件的长度,单位为MB
        /// </summary>
        /// <param name="filePath">文件的路径</param>        
        public static double GetFileSizeByMB( string filePath )
        {
            //创建一个文件对象
            FileInfo fi = new FileInfo( filePath );
            //获取文件的大小
            return ConvertHelper.ToDouble( ConvertHelper.ToDouble( fi.Length ) / 1024 / 1024 , 1 );
        }
        #endregion
        #region 获取指定目录中的文件列表
        /// <summary>
        /// 获取指定目录中所有文件列表
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>        
        public static string[] GetFileNames( string directoryPath )
        {
            //如果目录不存在,则抛出异常
            if ( !IsExistDirectory( directoryPath ) )
            {
                throw new FileNotFoundException();
            }
            //获取文件列表
            return Directory.GetFiles( directoryPath );
        }
        /// <summary>
        /// 获取指定目录及子目录中所有文件列表
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>
        /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
        /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
        /// <param name="isSearchChild">是否搜索子目录</param>
        public static string[] GetFileNames( string directoryPath, string searchPattern, bool isSearchChild )
        {
            //如果目录不存在,则抛出异常
            if ( !IsExistDirectory( directoryPath ) )
            {
                throw new FileNotFoundException();
            }
            try
            {
                if ( isSearchChild )
                {
                    return Directory.GetFiles( directoryPath, searchPattern, SearchOption.AllDirectories );
                }
                else
                {
                    return Directory.GetFiles( directoryPath, searchPattern, SearchOption.TopDirectoryOnly );
                }
            }
            catch ( IOException ex )
            {
                throw ex;
            }
        }
        #endregion
        #region 获取指定目录中的子目录列表
        /// <summary>
        /// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法.
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>        
        public static string[] GetDirectories( string directoryPath )
        {
            try
            {
                return Directory.GetDirectories( directoryPath );
            }
            catch ( IOException ex )
            {
                throw ex;
            }
        }
        /// <summary>
        /// 获取指定目录及子目录中所有子目录列表
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>
        /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
        /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
        /// <param name="isSearchChild">是否搜索子目录</param>
        public static string[] GetDirectories( string directoryPath, string searchPattern, bool isSearchChild )
        {
            try
            {
                if ( isSearchChild )
                {
                    return Directory.GetDirectories( directoryPath, searchPattern, SearchOption.AllDirectories );
                }
                else
                {
                    return Directory.GetDirectories( directoryPath, searchPattern, SearchOption.TopDirectoryOnly );
                }
            }
            catch ( IOException ex )
            {
                throw ex;
            }
        }
        #endregion              
        #region 向文本文件写入内容
        /// <summary>
        /// 向文本文件中写入内容
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        /// <param name="content">写入的内容</param>        
        public static void WriteText( string filePath, string content )
        {
            //向文件写入内容
            File.WriteAllText( filePath, content );
        }
        #endregion
        #region 向文本文件的尾部追加内容
        /// <summary>
        /// 向文本文件的尾部追加内容
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        /// <param name="content">写入的内容</param>
        public static void AppendText( string filePath, string content )
        {
            File.AppendAllText( filePath, content );
        }
        #endregion
        #region 将现有文件的内容复制到新文件中
        /// <summary>
        /// 将源文件的内容复制到目标文件中
        /// </summary>
        /// <param name="sourceFilePath">源文件的绝对路径</param>
        /// <param name="destFilePath">目标文件的绝对路径</param>
        public static void Copy( string sourceFilePath, string destFilePath )
        {
            File.Copy( sourceFilePath, destFilePath, true );
        }
        #endregion
        #region 将文件移动到指定目录
        /// <summary>
        /// 将文件移动到指定目录
        /// </summary>
        /// <param name="sourceFilePath">需要移动的源文件的绝对路径</param>
        /// <param name="descDirectoryPath">移动到的目录的绝对路径</param>
        public static void Move( string sourceFilePath,string descDirectoryPath )
        {            
            //获取源文件的名称
            string sourceFileName = GetFileName( sourceFilePath );           
            if ( IsExistDirectory( descDirectoryPath ) )
            {
                //如果目标中存在同名文件,则删除
                if ( IsExistFile( descDirectoryPath + "\\" + sourceFileName ) )
                {
                    DeleteFile( descDirectoryPath + "\\" + sourceFileName );
                }
                //将文件移动到指定目录
                File.Move( sourceFilePath, descDirectoryPath + "\\" + sourceFileName );
            }
        }
        #endregion
        #region 将流读取到缓冲区中
        /// <summary>
        /// 将流读取到缓冲区中
        /// </summary>
        /// <param name="stream">原始流</param>
        public static byte[] StreamToBytes( Stream stream )
        {
            try
            {
                //创建缓冲区
                byte[] buffer = new byte[stream.Length];
                //读取流
                stream.Read( buffer, 0, ConvertHelper.ToInt32( stream.Length ) );
                //返回流
                return buffer;
            }
            catch ( Exception ex )
            {
                LogHelper.WriteTraceLog( TraceLogLevel.Error, ex.Message );
                throw ex;
            }
            finally
            {
                //关闭流
                stream.Close();
            }
        }
        #endregion
        #region 将文件读取到缓冲区中
        /// <summary>
        /// 将文件读取到缓冲区中
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        public static byte[] FileToBytes( string filePath )
        {
            //获取文件的大小 
            int fileSize = GetFileSize( filePath );
            //创建一个临时缓冲区
            byte[] buffer = new byte[fileSize];
            //创建一个文件流
            FileInfo fi = new FileInfo( filePath );
            FileStream fs = fi.Open( FileMode.Open );
            try
            {
                //将文件流读入缓冲区
                fs.Read( buffer, 0, fileSize );
                return buffer;
            }
            catch ( IOException ex )
            {
                LogHelper.WriteTraceLog( TraceLogLevel.Error, ex.Message );
                throw ex;
            }
            finally
            {
                //关闭文件流
                fs.Close();
            }
        }
        #endregion       
        #region 将文件读取到字符串中
        /// <summary>
        /// 将文件读取到字符串中
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        public static string FileToString( string filePath )
        {
            return FileToString( filePath, BaseInfo.DefaultEncoding );
        }
        /// <summary>
        /// 将文件读取到字符串中
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        /// <param name="encoding">字符编码</param>
        public static string FileToString( string filePath,Encoding encoding )
        {
            //创建流读取器
            StreamReader reader = new StreamReader( filePath, encoding );
            try
            {
                //读取流
                return reader.ReadToEnd();
            }
            catch ( Exception ex )
            {
                LogHelper.WriteTraceLog( TraceLogLevel.Error, ex.Message );
                throw ex;
            }
            finally
            {
                //关闭流读取器
                reader.Close();
            }
        }
        #endregion
        #region 从文件的绝对路径中获取文件名( 包含扩展名 )
        /// <summary>
        /// 从文件的绝对路径中获取文件名( 包含扩展名 )
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>        
        public static string GetFileName( string filePath )
        {
            //获取文件的名称
            FileInfo fi = new FileInfo( filePath );
            return fi.Name;
        }
        #endregion
        #region 从文件的绝对路径中获取文件名( 不包含扩展名 )
        /// <summary>
        /// 从文件的绝对路径中获取文件名( 不包含扩展名 )
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>        
        public static string GetFileNameNoExtension( string filePath )
        {
            //获取文件的名称
            FileInfo fi = new FileInfo( filePath );
            return fi.Name.Split( '.' )[0];
        }
        #endregion
        #region 从文件的绝对路径中获取扩展名
        /// <summary>
        /// 从文件的绝对路径中获取扩展名
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>        
        public static string GetExtension( string filePath )
        {
            //获取文件的名称
            FileInfo fi = new FileInfo( filePath );
            return fi.Extension;
        }
        #endregion
        #region 清空指定目录
        /// <summary>
        /// 清空指定目录下所有文件及子目录,但该目录依然保存.
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>
        public static void ClearDirectory( string directoryPath )
        {
            if ( IsExistDirectory( directoryPath ) )
            {
                //删除目录中所有的文件
                string[] fileNames = GetFileNames( directoryPath );
                for ( int i = 0; i < fileNames.Length; i++ )
                {
                    DeleteFile( fileNames[i] );
                }
                //删除目录中所有的子目录
                string[] directoryNames = GetDirectories( directoryPath );
                for ( int i = 0; i < directoryNames.Length; i++ )
                {
                    DeleteDirectory( directoryNames[i] );
                }
            }            
        }
        #endregion
        #region 清空文件内容
        /// <summary>
        /// 清空文件内容
        /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        public static void ClearFile( string filePath )
        {
            //删除文件
            File.Delete( filePath );
            //重新创建该文件
            CreateFile( filePath );
        }
        #endregion
        #region 删除指定文件
        /// <summary>
       /// 删除指定文件
       /// </summary>
        /// <param name="filePath">文件的绝对路径</param>
        public static void DeleteFile( string filePath )
        {
            if ( IsExistFile( filePath ) )
            {
                File.Delete( filePath );
            }           
        }
        #endregion
        #region 删除指定目录
        /// <summary>
        /// 删除指定目录及其所有子目录
        /// </summary>
        /// <param name="directoryPath">指定目录的绝对路径</param>
        public static void DeleteDirectory( string directoryPath )
        {
            if ( IsExistDirectory( directoryPath ) )
            {
                Directory.Delete( directoryPath, true );
            }
        }
        #endregion
    }
}

转载于:https://www.cnblogs.com/eart/archive/2011/05/24/2056020.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/435047.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

修改linux开机画面

制作开机Logo方法一:Drivers/video/logo/logo_linux_clut224.ppm是默认的启动Logo图片&#xff0c;把自己的Logo图片&#xff08;png格式&#xff09;转换成ppm格式&#xff0c;替换这个文件&#xff0c; 同时删除logo_linux_clut224.c logo_linux_clut224.o文件 &#xff0c;重…

列表反向组成数字相加,并输出数组反向组成列表

# Definition for singly-linked list. #在节点ListNode定义中&#xff0c;定义为节点为结构变量。 #节点存储了两个变量&#xff1a;value 和 next。value 是这个节点的值&#xff0c;next 是指向下一节点的指针&#xff0c;当 next 为空指针时&#xff0c;这个节点是链表的最…

公众号jdk 获取手机号_如何获取公众号推文封面图

曾经有一张好看的图片摆在我的眼前&#xff0c;我却没能保存&#xff0c;等到失去的时候我才后悔莫及。如果上天能够给我一个再来一次的机会&#xff0c;我会对那张图片说三个字&#xff1a;我&#xff0c;要&#xff0c;你……现在大部分使用智能手机的小伙伴们&#xff0c;一…

container_of深入理解

container_of在linux头文件kernel.h中定义&#xff0c;如下&#xff1a; 14#ifndef offsetof15#define offsetof(TYPE, MEMBER) ((size_t) &((TYPE *)0)->MEMBER)16#endif1718#ifndef container_of19/**20 * container_of - cast a member of a structure out to the co…

正在读取软件包列表... 有错误!

正在读取软件包列表... 有错误&#xff01;E: Encountered a section with no Package: headerE: Problem with MergeList /var/lib/apt/lists/cn.archive.ubuntu.com_ubuntu_dists_natty_main_i18n_Translation-enE: 无法解析或打开软件包的列表或是状态文件。问题&#xff1a…

2021-10-19

下载的工具箱 找到下载工具箱位置 打开工具箱属性 出现错误1 无法启动配置 RasterCommander.ImageServer 解决方法

python自动控制库_Python最为神奇的库,可控制你的鼠标键盘自动运行!

Python最为神奇的库&#xff0c;可控制你的鼠标键盘自动运行&#xff01;这个库让你可以控制和监控输入设备。喜欢我还有更多干货入门知识&#xff0c;来公众号『程序员中文社区』聊聊吧。Python最为神奇的库&#xff0c;可控制你的鼠标键盘自动运行&#xff01;对于每一种输入…

iframe 自适应高度 跨域

window.navigator.Allframesnull;window.navigator.Allframes { iframe1: window }; //根据页面name属性查找到子页面所在Ifame对象 window.navigator.getFrameByNamefunction(oName){ return this.Allframes[oName] }; //将一个Iframe对象注册到window.navigator.Al…

【转】Windows服务调试技巧

关于调试windows service, 其实这是一个老生常谈的问题了. 通常的处理办法是, 在service运行后, 在调试器中选择attach to process. 然而这种做法也有一定的局限性, 例如在service启动时的OnStart事件中的代码, 基本上很难调试. 往往当attach到我们的service的时候, 这部分代码…

visual studio 没有属性页_驯龙物语10月14日更新|新增快捷购买页签

更新公告大家好&#xff0c;我是小白龙&#xff0c;很高兴又与大家见面啦&#xff01;维利克洛大陆又迎来了新内容&#xff0c;守护者们要仔细阅读看到最后喔&#xff01;更新时间本次更新于10月14日6:00-7:00进行&#xff0c;视更新进度可能提前开服或顺延&#xff0c;各位守护…

JDK1.6

JDK(Java Development Kit)是Sun Microsystems针对Java开发员的产品。自从Java推出以来&#xff0c;JDK已经成为使用最广泛的Java SDK。JDK 是整个Java的核心&#xff0c;包括了Java运行环境&#xff0c;Java工具和Java基础的类库。 java环境变量配置&#xff1a; 如果是Window…

AE开发右键缩放至图层

添加 右键的控件 将控件添加至axtoccontrol 双击进入点击事件 private void 缩放至图层ToolStripMenuItem_Click(object sender, EventArgs e){axMapControl1.ActiveView.FullExtent = m_Layer.AreaOfInterest;axMapControl1.ActiveView.Refresh();axTOCControl1.Update();}…

快速幂取余

快速幂取模算法&#xff0c;留着以后慢慢研究 long long modExp(long long a,long long b,long long n){ long long t,y; t 1; y a; while(b){ if(b % 2) t t * y % n; y y * y % n; b >> 1; } return t;} 转载于:https:/…

nginx源码学习资源

nginx源码学习是一个痛苦又快乐的过程&#xff0c;下面列出了一些nginx的学习资源。 首先要做的当然是下载一份nginx源码&#xff0c;可以从nginx官方网站下载一份最新的。 看了nginx源码&#xff0c;发现这是一份完全没有注释&#xff0c;完全没有配置文档的代码。 现在你最希…

C#打开文件和文件夹

打开文件夹 private void buttonX2_Click(object sender, EventArgs e){//输出文件路径FolderBrowserDialog dialog new FolderBrowserDialog();//提示用户打开文件窗体dialog.Description "请选择文件路径";if (dialog.ShowDialog() DialogResult.OK){textBoxsav…

通过JavaScript操作HTML中select标签

添加&#xff1a; Js代码1.function selectChange() 2.{ 3. var seldocument.getElementById("select1"); 4. Option option new Option("Text","Value"); 5. sel.add(option); 6.} function selectChange(){ var seldocument.get…

标签机二次开发

1. BPLA_OpenComEx("com1",38400,1,1000) 打开串口 2. BPLA_Set(2,0,1) 设置打印机基本参数&#xff0c;如果设置出纸方式为“撕离”&#xff0c;那么需要第3.1步&#xff0c;如果设置出纸方式为“回卷”&#xff0c;需要第3.2步 如果打印机有碳带&#xff0c;需要设…

动漫的python语言代码大全_下载动漫壁纸-Python代码

本帖最后由 我心她有丶 于 2020-4-16 19:28 编辑前段时间在论坛找到一个下载动漫壁纸的软件&#xff0c;还挺好用的&#xff0c;这几天突然用一下&#xff0c;下载不出图片&#xff0c;下载的一片白&#xff0c;然后分析了下他的软件&#xff0c;得到了一个地址&#xff1a; ht…