asp.net常用的文件与文件类型_asp.net常用的文件与文件夹操作类

更新时间:2017-02-13    来源:php常用代码    手机版     字体:

【www.bbyears.com--php常用代码】

asp教程.net常用的文件与文件夹操作类

#region 引用命名空间
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
#endregion
namespace CommonUtilities
{
    ///
    /// 文件操作类
    ///

    public class FileHelper
    {
        #region 检测指定目录是否存在
        ///
        /// 检测指定目录是否存在
        ///

        /// 目录的绝对路径        
        public static bool IsExistDirectory( string directoryPath )
        {
            return Directory.Exists( directoryPath );
        }
        #endregion
        #region 检测指定文件是否存在
        ///
        /// 检测指定文件是否存在,如果存在则返回true。
        ///

        /// 文件的绝对路径        
        public static bool IsExistFile( string filePath )
        {
            return File.Exists( filePath );            
        }
        #endregion
        #region 检测指定目录是否为空
        ///
        /// 检测指定目录是否为空
        ///

        /// 指定目录的绝对路径        
        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 检测指定目录中是否存在指定的文件
        ///
        /// 检测指定目录中是否存在指定的文件,若要搜索子目录请使用重载方法.
        ///

        /// 指定目录的绝对路径
        /// 模式字符串,"*"代表0或N个字符,"?"代表1个字符。
        /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。        
        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;
            }
        }
        ///
        /// 检测指定目录中是否存在指定的文件
        ///

        /// 指定目录的绝对路径
        /// 模式字符串,"*"代表0或N个字符,"?"代表1个字符。
        /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。 
        /// 是否搜索子目录
        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 创建一个目录
        ///
        /// 创建一个目录
        ///

        /// 目录的绝对路径
        public static void CreateDirectory( string directoryPath )
        {
            //如果目录不存在则创建该目录
            if ( !IsExistDirectory( directoryPath ) )
            {
                Directory.CreateDirectory( directoryPath );
            }
        }
        #endregion
        #region 创建一个文件
        ///
        /// 创建一个文件。
        ///

        /// 文件的绝对路径
        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;
            }
        }
        ///
        /// 创建一个文件,并将字节流写入文件。
        ///

        /// 文件的绝对路径
        /// 二进制流数据
        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 获取文本文件的行数
        ///
        /// 获取文本文件的行数
        ///

        /// 文件的绝对路径        
        public static int GetLineCount( string filePath )
        {
            //将文本文件的各行读到一个字符串数组中
            string[] rows = File.ReadAllLines( filePath );
            //返回行数
            return rows.Length;
        }
        #endregion
        #region 获取一个文件的长度
        ///
        /// 获取一个文件的长度,单位为Byte
        ///

        /// 文件的绝对路径        
        public static int GetFileSize( string filePath )
        {
            //创建一个文件对象
            FileInfo fi = new FileInfo( filePath );
            //获取文件的大小
            return (int)fi.Length;
        }
        ///
        /// 获取一个文件的长度,单位为KB
        ///

        /// 文件的路径        
        public static double GetFileSizeByKB( string filePath )
        {
            //创建一个文件对象
            FileInfo fi = new FileInfo( filePath );           
            //获取文件的大小
            return ConvertHelper.ToDouble( ConvertHelper.ToDouble( fi.Length ) / 1024 , 1 );
        }
        ///
        /// 获取一个文件的长度,单位为MB
        ///

        /// 文件的路径        
        public static double GetFileSizeByMB( string filePath )
        {
            //创建一个文件对象
            FileInfo fi = new FileInfo( filePath );
            //获取文件的大小
            return ConvertHelper.ToDouble( ConvertHelper.ToDouble( fi.Length ) / 1024 / 1024 , 1 );
        }
        #endregion
        #region 获取指定目录中的文件列表
        ///
        /// 获取指定目录中所有文件列表
        ///

        /// 指定目录的绝对路径        
        public static string[] GetFileNames( string directoryPath )
        {
            //如果目录不存在,则抛出异常
            if ( !IsExistDirectory( directoryPath ) )
            {
                throw new FileNotFoundException();
            }
            //获取文件列表
            return Directory.GetFiles( directoryPath );
        }
        ///
        /// 获取指定目录及子目录中所有文件列表
        ///

        /// 指定目录的绝对路径
        /// 模式字符串,"*"代表0或N个字符,"?"代表1个字符。
        /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。
        /// 是否搜索子目录
        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 获取指定目录中的子目录列表
        ///
        /// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法.
        ///

        /// 指定目录的绝对路径        
        public static string[] GetDirectories( string directoryPath )
        {
            try
            {
                return Directory.GetDirectories( directoryPath );
            }
            catch ( IOException ex )
            {
                throw ex;
            }
        }
        ///
        /// 获取指定目录及子目录中所有子目录列表
        ///

        /// 指定目录的绝对路径
        /// 模式字符串,"*"代表0或N个字符,"?"代表1个字符。
        /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。
        /// 是否搜索子目录
        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 向文本文件写入内容
        ///
        /// 向文本文件中写入内容
        ///

        /// 文件的绝对路径
        /// 写入的内容        
        public static void WriteText( string filePath, string content )
        {
            //向文件写入内容
            File.WriteAllText( filePath, content );
        }
        #endregion
        #region 向文本文件的尾部追加内容
        ///
        /// 向文本文件的尾部追加内容
        ///

        /// 文件的绝对路径
        /// 写入的内容
        public static void AppendText( string filePath, string content )
        {
            File.AppendAllText( filePath, content );
        }
        #endregion
        #region 将现有文件的内容复制到新文件中
        ///
        /// 将源文件的内容复制到目标文件中
        ///

        /// 源文件的绝对路径
        /// 目标文件的绝对路径
        public static void Copy( string sourceFilePath, string destFilePath )
        {
            File.Copy( sourceFilePath, destFilePath, true );
        }
        #endregion
        #region 将文件移动到指定目录
        ///
        /// 将文件移动到指定目录
        ///

        /// 需要移动的源文件的绝对路径
        /// 移动到的目录的绝对路径
        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 将流读取到缓冲区中
        ///
        /// 将流读取到缓冲区中
        ///

        /// 原始流
        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 将文件读取到缓冲区中
        ///
        /// 将文件读取到缓冲区中
        ///

        /// 文件的绝对路径
        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 将文件读取到字符串中
        ///
        /// 将文件读取到字符串中
        ///

        /// 文件的绝对路径
        public static string FileToString( string filePath )
        {
            return FileToString( filePath, BaseInfo.DefaultEncoding );
        }
        ///
        /// 将文件读取到字符串中
        ///

        /// 文件的绝对路径
        /// 字符编码
        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 从文件的绝对路径中获取文件名( 包含扩展名 )
        ///
        /// 从文件的绝对路径中获取文件名( 包含扩展名 )
        ///

        /// 文件的绝对路径        
        public static string GetFileName( string filePath )
        {
            //获取文件的名称
            FileInfo fi = new FileInfo( filePath );
            return fi.Name;
        }
        #endregion
        #region 从文件的绝对路径中获取文件名( 不包含扩展名 )
        ///
        /// 从文件的绝对路径中获取文件名( 不包含扩展名 )
        ///

        /// 文件的绝对路径        
        public static string GetFileNameNoExtension( string filePath )
        {
            //获取文件的名称
            FileInfo fi = new FileInfo( filePath );
            return fi.Name.Split( "." )[0];
        }
        #endregion
        #region 从文件的绝对路径中获取扩展名
        ///
        /// 从文件的绝对路径中获取扩展名
        ///

        /// 文件的绝对路径        
        public static string GetExtension( string filePath )
        {
            //获取文件的名称
            FileInfo fi = new FileInfo( filePath );
            return fi.Extension;
        }
        #endregion
        #region 清空指定目录
        ///
        /// 清空指定目录下所有文件及子目录,但该目录依然保存.
        ///

        /// 指定目录的绝对路径
        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 清空文件内容
        ///
        /// 清空文件内容
        ///

        /// 文件的绝对路径
        public static void ClearFile( string filePath )
        {
            //删除文件
            File.Delete( filePath );
            //重新创建该文件
            CreateFile( filePath );
        }
        #endregion
        #region 删除指定文件
        ///
       /// 删除指定文件
       ///

        /// 文件的绝对路径
        public static void DeleteFile( string filePath )
        {
            if ( IsExistFile( filePath ) )
            {
                File.Delete( filePath );
            }           
        }
        #endregion
        #region 删除指定目录
        ///
        /// 删除指定目录及其所有子目录
        ///

        /// 指定目录的绝对路径
        public static void DeleteDirectory( string directoryPath )
        {
            if ( IsExistDirectory( directoryPath ) )
            {
                Directory.Delete( directoryPath, true );
            }
        }
        #endregion
    }
}

文件类二

要创建的文件路径
public void CreateFolder(string FolderPathName)
{
if(FolderPathName.Trim().Length> 0)
{
try
{
string CreatePath = System.Web.HttpContext.Current.Server.MapPath

("../../../Images/"+FolderPathName).ToString();
if(!Directory.Exists(CreatePath))
{
Directory.CreateDirectory(CreatePath);
}
}
catch
{
throw;
}
}
}

/**////
/// 删除一个文件夹下面的字文件夹和文件
///
///
public void DeleteChildFolder(string FolderPathName)
{
if(FolderPathName.Trim().Length> 0)
{
try
{
string CreatePath = System.Web.HttpContext.Current.Server.MapPath

(FolderPathName).ToString();
if(Directory.Exists(CreatePath))
{
Directory.Delete(CreatePath,true);
}
}
catch
{
throw;
}
}
}

/**////
/// 删除一个文件
///
///
public void DeleteFile(string FilePathName)
{
try
{
FileInfo DeleFile = new FileInfo(System.Web.HttpContext.Current.Server.MapPath

(FilePathName).ToString());
DeleFile.Delete();
}
catch
{
}
}
public void CreateFile(string FilePathName)
{
try
{
//创建文件夹
string[] strPath= FilePathName.Split("/");
CreateFolder(FilePathName.Replace("/" + strPath[strPath.Length-1].ToString(),"")); //创建文件


FileInfo CreateFile =new FileInfo(System.Web.HttpContext.Current.Server.MapPath

(FilePathName).ToString()); //创建文件
if(!CreateFile.Exists)
{
FileStream FS=CreateFile.Create();
FS.Close();
}
}
catch
{
}
}
/**////
/// 删除整个文件夹及其字文件夹和文件
///
///
public void DeleParentFolder(string FolderPathName)
{
try
{
DirectoryInfo DelFolder = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath

(FolderPathName).ToString());
if(DelFolder.Exists)
{
DelFolder.Delete();
}
}
catch
{
}
}
/**////
/// 在文件里追加内容
///
///
public void ReWriteReadinnerText(string FilePathName,string WriteWord)
{
try
{
//建立文件夹和文件
//CreateFolder(FilePathName);
CreateFile(FilePathName);
//得到原来文件的内容
FileStream FileRead=new FileStream(System.Web.HttpContext.Current.Server.MapPath

(FilePathName).ToString(),FileMode.Open,FileAccess.ReadWrite);
StreamReader FileReadWord=new StreamReader(FileRead,System.Text.Encoding.Default);
string OldString = FileReadWord.ReadToEnd().ToString();
OldString = OldString + WriteWord;
//把新的内容重新写入
StreamWriter FileWrite=new StreamWriter(FileRead,System.Text.Encoding.Default);
FileWrite.Write(WriteWord);
//关闭
FileWrite.Close();
FileReadWord.Close();
FileRead.Close();
}
catch
{
// throw;
}
}

/**////
/// 在文件里追加内容
///
///
public string ReaderFileData(string FilePathName)
{
try
{

FileStream FileRead=new FileStream(System.Web.HttpContext.Current.Server.MapPath

(FilePathName).ToString(),FileMode.Open,FileAccess.Read);
StreamReader FileReadWord=new StreamReader(FileRead,System.Text.Encoding.Default);
string TxtString = FileReadWord.ReadToEnd().ToString();
//关闭
FileReadWord.Close();
FileRead.Close();
return TxtString;
}
catch
{
throw;
}
}
/**////
/// 读取文件夹的文件
///
///
///
public DirectoryInfo checkValidSessionPath(string FilePathName)
{
try
{
DirectoryInfo MainDir = new DirectoryInfo(System.Web.HttpContext.Current.Server.MapPath

(FilePathName));
return MainDir;

}
catch
{
throw;
}
}
}
}

本文来源:http://www.bbyears.com/jiaocheng/30474.html

猜你感兴趣