asp.net文件操作类

asp.net文件操作类

001/**
002文件操作类
003**/
004#region 引用命名空间
005using System;
006using System.Collections.Generic;
007using System.Text;
008using System.IO;
009#endregion
010namespace CommonUtilities
011{
012    /// <summary>
013    /// 文件操作类
014    /// </summary>
015    public class FileHelper
016    {
017        #region 检测指定目录是否存在
018        /// <summary>
019        /// 检测指定目录是否存在
020        /// </summary>
021        /// <param name="directoryPath">目录的绝对路径</param>        
022        public static bool IsExistDirectory( string directoryPath )
023        {
024            return Directory.Exists( directoryPath );
025        }
026        #endregion
027        #region 检测指定文件是否存在
028        /// <summary>
029        /// 检测指定文件是否存在,如果存在则返回true。
030        /// </summary>
031        /// <param name="filePath">文件的绝对路径</param>        
032        public static bool IsExistFile( string filePath )
033        {
034            return File.Exists( filePath );            
035        }
036        #endregion
037        #region 检测指定目录是否为空
038        /// <summary>
039        /// 检测指定目录是否为空
040        /// </summary>
041        /// <param name="directoryPath">指定目录的绝对路径</param>        
042        public static bool IsEmptyDirectory( string directoryPath )
043        {
044            try
045            {
046                //判断是否存在文件
047                string[] fileNames = GetFileNames( directoryPath );
048                if ( fileNames.Length > 0 )
049                {
050                    return false;
051                }
052                //判断是否存在文件夹
053                string[] directoryNames = GetDirectories( directoryPath );
054                if ( directoryNames.Length > 0 )
055                {
056                    return false;
057                }
058                return true;
059            }
060            catch ( Exception ex )
061            {
062                LogHelper.WriteTraceLog( TraceLogLevel.Error, ex.Message );
063                return true;
064            }
065        }
066        #endregion
067        #region 检测指定目录中是否存在指定的文件
068        /// <summary>
069        /// 检测指定目录中是否存在指定的文件,若要搜索子目录请使用重载方法.
070        /// </summary>
071        /// <param name="directoryPath">指定目录的绝对路径</param>
072        /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
073        /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>        
074        public static bool Contains( string directoryPath, string searchPattern )
075        {
076            try
077            {
078                //获取指定的文件列表
079                string[] fileNames = GetFileNames( directoryPath, searchPattern, false );
080                //判断指定文件是否存在
081                if ( fileNames.Length == 0 )
082                {
083                    return false;
084                }
085                else
086                {
087                    return true;
088                }
089            }
090            catch ( Exception ex )
091            {
092                LogHelper.WriteTraceLog( TraceLogLevel.Error, ex.Message );
093                return false;
094            }
095        }
096        /// <summary>
097        /// 检测指定目录中是否存在指定的文件
098        /// </summary>
099        /// <param name="directoryPath">指定目录的绝对路径</param>
100        /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
101        /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param> 
102        /// <param name="isSearchChild">是否搜索子目录</param>
103        public static bool Contains( string directoryPath, string searchPattern, bool isSearchChild )
104        {
105            try
106            {
107                //获取指定的文件列表
108                string[] fileNames = GetFileNames( directoryPath, searchPattern, true );
109                //判断指定文件是否存在
110                if ( fileNames.Length == 0 )
111                {
112                    return false;
113                }
114                else
115                {
116                    return true;
117                }
118            }
119            catch ( Exception ex )
120            {
121                LogHelper.WriteTraceLog( TraceLogLevel.Error, ex.Message );
122                return false;
123            }
124        }
125        #endregion       
126        #region 创建一个目录
127        /// <summary>
128        /// 创建一个目录
129        /// </summary>
130        /// <param name="directoryPath">目录的绝对路径</param>
131        public static void CreateDirectory( string directoryPath )
132        {
133            //如果目录不存在则创建该目录
134            if ( !IsExistDirectory( directoryPath ) )
135            {
136                Directory.CreateDirectory( directoryPath );
137            }
138        }
139        #endregion
140        #region 创建一个文件
141        /// <summary>
142        /// 创建一个文件。
143        /// </summary>
144        /// <param name="filePath">文件的绝对路径</param>
145        public static void CreateFile( string filePath )
146        {
147            try
148            {
149                //如果文件不存在则创建该文件
150                if ( !IsExistFile( filePath ) )
151                {
152                    //创建一个FileInfo对象
153                    FileInfo file = new FileInfo( filePath );
154                    //创建文件
155                    FileStream fs = file.Create();
156                    //关闭文件流
157                    fs.Close();
158                }
159            }
160            catch ( Exception ex )
161            {
162                LogHelper.WriteTraceLog( TraceLogLevel.Error, ex.Message );
163                throw ex;
164            }
165        }
166        /// <summary>
167        /// 创建一个文件,并将字节流写入文件。
168        /// </summary>
169        /// <param name="filePath">文件的绝对路径</param>
170        /// <param name="buffer">二进制流数据</param>
171        public static void CreateFile( string filePath, byte[] buffer )
172        {
173            try
174            {
175                //如果文件不存在则创建该文件
176                if ( !IsExistFile( filePath ) )
177                {
178                    //创建一个FileInfo对象
179                    FileInfo file = new FileInfo( filePath );
180                    //创建文件
181                    FileStream fs = file.Create();
182                    //写入二进制流
183                    fs.Write( buffer, 0, buffer.Length );
184                    //关闭文件流
185                    fs.Close();
186                }
187            }
188            catch ( Exception ex )
189            {
190                LogHelper.WriteTraceLog( TraceLogLevel.Error, ex.Message );
191                throw ex;
192            }
193        }
194        #endregion
195        #region 获取文本文件的行数
196        /// <summary>
197        /// 获取文本文件的行数
198        /// </summary>
199        /// <param name="filePath">文件的绝对路径</param>        
200        public static int GetLineCount( string filePath )
201        {
202            //将文本文件的各行读到一个字符串数组中
203            string[] rows = File.ReadAllLines( filePath );
204            //返回行数
205            return rows.Length;
206        }
207        #endregion
208        #region 获取一个文件的长度
209        /// <summary>
210        /// 获取一个文件的长度,单位为Byte
211        /// </summary>
212        /// <param name="filePath">文件的绝对路径</param>        
213        public static int GetFileSize( string filePath )
214        {
215            //创建一个文件对象
216            FileInfo fi = new FileInfo( filePath );
217            //获取文件的大小
218            return (int)fi.Length;
219        }
220        /// <summary>
221        /// 获取一个文件的长度,单位为KB
222        /// </summary>
223        /// <param name="filePath">文件的路径</param>        
224        public static double GetFileSizeByKB( string filePath )
225        {
226            //创建一个文件对象
227            FileInfo fi = new FileInfo( filePath );           
228            //获取文件的大小
229            return ConvertHelper.ToDouble( ConvertHelper.ToDouble( fi.Length ) / 1024 , 1 );
230        }
231        /// <summary>
232        /// 获取一个文件的长度,单位为MB
233        /// </summary>
234        /// <param name="filePath">文件的路径</param>        
235        public static double GetFileSizeByMB( string filePath )
236        {
237            //创建一个文件对象
238            FileInfo fi = new FileInfo( filePath );
239            //获取文件的大小
240            return ConvertHelper.ToDouble( ConvertHelper.ToDouble( fi.Length ) / 1024 / 1024 , 1 );
241        }
242        #endregion
243        #region 获取指定目录中的文件列表
244        /// <summary>
245        /// 获取指定目录中所有文件列表
246        /// </summary>
247        /// <param name="directoryPath">指定目录的绝对路径</param>        
248        public static string[] GetFileNames( string directoryPath )
249        {
250            //如果目录不存在,则抛出异常
251            if ( !IsExistDirectory( directoryPath ) )
252            {
253                throw new FileNotFoundException();
254            }
255            //获取文件列表
256            return Directory.GetFiles( directoryPath );
257        }
258        /// <summary>
259        /// 获取指定目录及子目录中所有文件列表
260        /// </summary>
261        /// <param name="directoryPath">指定目录的绝对路径</param>
262        /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
263        /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
264        /// <param name="isSearchChild">是否搜索子目录</param>
265        public static string[] GetFileNames( string directoryPath, string searchPattern, bool isSearchChild )
266        {
267            //如果目录不存在,则抛出异常
268            if ( !IsExistDirectory( directoryPath ) )
269            {
270                throw new FileNotFoundException();
271            }
272            try
273            {
274                if ( isSearchChild )
275                {
276                    return Directory.GetFiles( directoryPath, searchPattern, SearchOption.AllDirectories );
277                }
278                else
279                {
280                    return Directory.GetFiles( directoryPath, searchPattern, SearchOption.TopDirectoryOnly );
281                }
282            }
283            catch ( IOException ex )
284            {
285                throw ex;
286            }
287        }
288        #endregion
289        #region 获取指定目录中的子目录列表
290        /// <summary>
291        /// 获取指定目录中所有子目录列表,若要搜索嵌套的子目录列表,请使用重载方法.
292        /// </summary>
293        /// <param name="directoryPath">指定目录的绝对路径</param>        
294        public static string[] GetDirectories( string directoryPath )
295        {
296            try
297            {
298                return Directory.GetDirectories( directoryPath );
299            }
300            catch ( IOException ex )
301            {
302                throw ex;
303            }
304        }
305        /// <summary>
306        /// 获取指定目录及子目录中所有子目录列表
307        /// </summary>
308        /// <param name="directoryPath">指定目录的绝对路径</param>
309        /// <param name="searchPattern">模式字符串,"*"代表0或N个字符,"?"代表1个字符。
310        /// 范例:"Log*.xml"表示搜索所有以Log开头的Xml文件。</param>
311        /// <param name="isSearchChild">是否搜索子目录</param>
312        public static string[] GetDirectories( string directoryPath, string searchPattern, bool isSearchChild )
313        {
314            try
315            {
316                if ( isSearchChild )
317                {
318                    return Directory.GetDirectories( directoryPath, searchPattern, SearchOption.AllDirectories );
319                }
320                else
321                {
322                    return Directory.GetDirectories( directoryPath, searchPattern, SearchOption.TopDirectoryOnly );
323                }
324            }
325            catch ( IOException ex )
326            {
327                throw ex;
328            }
329        }
330        #endregion              
331        #region 向文本文件写入内容
332        /// <summary>
333        /// 向文本文件中写入内容
334        /// </summary>
335        /// <param name="filePath">文件的绝对路径</param>
336        /// <param name="content">写入的内容</param>        
337        public static void WriteText( string filePath, string content )
338        {
339            //向文件写入内容
340            File.WriteAllText( filePath, content );
341        }
342        #endregion
343        #region 向文本文件的尾部追加内容
344        /// <summary>
345        /// 向文本文件的尾部追加内容
346        /// </summary>
347        /// <param name="filePath">文件的绝对路径</param>
348        /// <param name="content">写入的内容</param>
349        public static void AppendText( string filePath, string content )
350        {
351            File.AppendAllText( filePath, content );
352        }
353        #endregion
354        #region 将现有文件的内容复制到新文件中
355        /// <summary>
356        /// 将源文件的内容复制到目标文件中
357        /// </summary>
358        /// <param name="sourceFilePath">源文件的绝对路径</param>
359        /// <param name="destFilePath">目标文件的绝对路径</param>
360        public static void Copy( string sourceFilePath, string destFilePath )
361        {
362            File.Copy( sourceFilePath, destFilePath, true );
363        }
364        #endregion
365        #region 将文件移动到指定目录
366        /// <summary>
367        /// 将文件移动到指定目录
368        /// </summary>
369        /// <param name="sourceFilePath">需要移动的源文件的绝对路径</param>
370        /// <param name="descDirectoryPath">移动到的目录的绝对路径</param>
371        public static void Move( string sourceFilePath,string descDirectoryPath )
372        {            
373            //获取源文件的名称
374            string sourceFileName = GetFileName( sourceFilePath );           
375            if ( IsExistDirectory( descDirectoryPath ) )
376            {
377                //如果目标中存在同名文件,则删除
378                if ( IsExistFile( descDirectoryPath + "\\" + sourceFileName ) )
379                {
380                    DeleteFile( descDirectoryPath + "\\" + sourceFileName );
381                }
382                //将文件移动到指定目录
383                File.Move( sourceFilePath, descDirectoryPath + "\\" + sourceFileName );
384            }
385        }
386        #endregion
387        #region 将流读取到缓冲区中
388        /// <summary>
389        /// 将流读取到缓冲区中
390        /// </summary>
391        /// <param name="stream">原始流</param>
392        public static byte[] StreamToBytes( Stream stream )
393        {
394            try
395            {
396                //创建缓冲区
397                byte[] buffer = new byte[stream.Length];
398                //读取流
399                stream.Read( buffer, 0, ConvertHelper.ToInt32( stream.Length ) );
400                //返回流
401                return buffer;
402            }
403            catch ( Exception ex )
404            {
405                LogHelper.WriteTraceLog( TraceLogLevel.Error, ex.Message );
406                throw ex;
407            }
408            finally
409            {
410                //关闭流
411                stream.Close();
412            }
413        }
414        #endregion
415        #region 将文件读取到缓冲区中
416        /// <summary>
417        /// 将文件读取到缓冲区中
418        /// </summary>
419        /// <param name="filePath">文件的绝对路径</param>
420        public static byte[] FileToBytes( string filePath )
421        {
422            //获取文件的大小 
423            int fileSize = GetFileSize( filePath );
424            //创建一个临时缓冲区
425            byte[] buffer = new byte[fileSize];
426            //创建一个文件流
427            FileInfo fi = new FileInfo( filePath );
428            FileStream fs = fi.Open( FileMode.Open );
429            try
430            {
431                //将文件流读入缓冲区
432                fs.Read( buffer, 0, fileSize );
433                return buffer;
434            }
435            catch ( IOException ex )
436            {
437                LogHelper.WriteTraceLog( TraceLogLevel.Error, ex.Message );
438                throw ex;
439            }
440            finally
441            {
442                //关闭文件流
443                fs.Close();
444            }
445        }
446        #endregion       
447        #region 将文件读取到字符串中
448        /// <summary>
449        /// 将文件读取到字符串中
450        /// </summary>
451        /// <param name="filePath">文件的绝对路径</param>
452        public static string FileToString( string filePath )
453        {
454            return FileToString( filePath, BaseInfo.DefaultEncoding );
455        }
456        /// <summary>
457        /// 将文件读取到字符串中
458        /// </summary>
459        /// <param name="filePath">文件的绝对路径</param>
460        /// <param name="encoding">字符编码</param>
461        public static string FileToString( string filePath,Encoding encoding )
462        {
463            //创建流读取器
464            StreamReader reader = new StreamReader( filePath, encoding );
465            try
466            {
467                //读取流
468                return reader.ReadToEnd();
469            }
470            catch ( Exception ex )
471            {
472                LogHelper.WriteTraceLog( TraceLogLevel.Error, ex.Message );
473                throw ex;
474            }
475            finally
476            {
477                //关闭流读取器
478                reader.Close();
479            }
480        }
481        #endregion
482        #region 从文件的绝对路径中获取文件名( 包含扩展名 )
483        /// <summary>
484        /// 从文件的绝对路径中获取文件名( 包含扩展名 )
485        /// </summary>
486        /// <param name="filePath">文件的绝对路径</param>        
487        public static string GetFileName( string filePath )
488        {
489            //获取文件的名称
490            FileInfo fi = new FileInfo( filePath );
491            return fi.Name;
492        }
493        #endregion
494        #region 从文件的绝对路径中获取文件名( 不包含扩展名 )
495        /// <summary>
496        /// 从文件的绝对路径中获取文件名( 不包含扩展名 )
497        /// </summary>
498        /// <param name="filePath">文件的绝对路径</param>        
499        public static string GetFileNameNoExtension( string filePath )
500        {
501            //获取文件的名称
502            FileInfo fi = new FileInfo( filePath );
503            return fi.Name.Split( '.' )[0];
504        }
505        #endregion
506        #region 从文件的绝对路径中获取扩展名
507        /// <summary>
508        /// 从文件的绝对路径中获取扩展名
509        /// </summary>
510        /// <param name="filePath">文件的绝对路径</param>        
511        public static string GetExtension( string filePath )
512        {
513            //获取文件的名称
514            FileInfo fi = new FileInfo( filePath );
515            return fi.Extension;
516        }
517        #endregion
518        #region 清空指定目录
519        /// <summary>
520        /// 清空指定目录下所有文件及子目录,但该目录依然保存.
521        /// </summary>
522        /// <param name="directoryPath">指定目录的绝对路径</param>
523        public static void ClearDirectory( string directoryPath )
524        {
525            if ( IsExistDirectory( directoryPath ) )
526            {
527                //删除目录中所有的文件
528                string[] fileNames = GetFileNames( directoryPath );
529                for int i = 0; i < fileNames.Length; i++ )
530                {
531                    DeleteFile( fileNames[i] );
532                }
533                //删除目录中所有的子目录
534                string[] directoryNames = GetDirectories( directoryPath );
535                for int i = 0; i < directoryNames.Length; i++ )
536                {
537                    DeleteDirectory( directoryNames[i] );
538                }
539            }            
540        }
541        #endregion
542        #region 清空文件内容
543        /// <summary>
544        /// 清空文件内容
545        /// </summary>
546        /// <param name="filePath">文件的绝对路径</param>
547        public static void ClearFile( string filePath )
548        {
549            //删除文件
550            File.Delete( filePath );
551            //重新创建该文件
552            CreateFile( filePath );
553        }
554        #endregion
555        #region 删除指定文件
556        /// <summary>
557       /// 删除指定文件
558       /// </summary>
559        /// <param name="filePath">文件的绝对路径</param>
560        public static void DeleteFile( string filePath )
561        {
562            if ( IsExistFile( filePath ) )
563            {
564                File.Delete( filePath );
565            }           
566        }
567        #endregion
568        #region 删除指定目录
569        /// <summary>
570        /// 删除指定目录及其所有子目录
571        /// </summary>
572        /// <param name="directoryPath">指定目录的绝对路径</param>
573        public static void DeleteDirectory( string directoryPath )
574        {
575            if ( IsExistDirectory( directoryPath ) )
576            {
577                Directory.Delete( directoryPath, true );
578            }
579        }
580        #endregion
581    }
582}

转载于:https://www.cnblogs.com/feilong3540717/archive/2011/10/27/2225904.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值