文件操作工具类 FileUtility

最近一直在研究 Smart Client 的 Smart Update 开发,从 Microsoft Updater Application Block v2.0 里面学到了很多东西,这里不得不佩服 Enterprise Library 的设计,设计模式和 XML 的运用使得 Enterprise Library 的扩展性很强,设计十分优美,是学习 OOP 的好范例。本人看了之后感叹自己写的代码大部分还是面向过程。
Enterprise Library 的广告就做到这里了,下面一个操作文件的工具类是从 Microsoft Updater Application Block v2.0 里面取出来的,感觉具有一定的参考价值,希望对大家有帮助。
None.gif using  System;
None.gif
using  System.IO;
None.gif
using  System.Runtime.InteropServices;
None.gif
None.gif
namespace  RapidTier
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// Indicates how to proceed with the move file operation. 
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    [Flags]
InBlock.gif    
public enum MoveFileFlag : int
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Perform a default move funtion.
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        None                = 0x00000000,
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// If the target file exists, the move function will replace it.
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        ReplaceExisting     = 0x00000001,
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// If the file is to be moved to a different volume, 
InBlock.gif        
/// the function simulates the move by using the CopyFile and DeleteFile functions. 
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        CopyAllowed         = 0x00000002,
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// The system does not move the file until the operating system is restarted. 
InBlock.gif        
/// The system moves the file immediately after AUTOCHK is executed, but before 
InBlock.gif        
/// creating any paging files. Consequently, this parameter enables the function 
InBlock.gif        
/// to delete paging files from previous startups. 
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        DelayUntilReboot    = 0x00000004,
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// The function does not return until the file has actually been moved on the disk. 
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        WriteThrough        = 0x00000008,
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Reserved for future use.
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        CreateHardLink      = 0x00000010,
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// The function fails if the source file is a link source, but the file cannot be tracked after the move. This situation can occur if the destination is a volume formatted with the FAT file system.
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        FailIfNotTrackable    = 0x00000020,
ExpandedSubBlockEnd.gif    }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif    
/**//// <summary>
InBlock.gif    
/// Provides certain utilities used by configuration processors, such as correcting file paths.
ExpandedSubBlockEnd.gif    
/// </summary>

InBlock.gif    public sealed class FileUtility
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Constructor#region Constructor
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Default constructor.
ExpandedSubBlockEnd.gif        
/// </summary>

InBlock.gif        private FileUtility()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Public members#region Public members
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Returns whether the path is a UNC path.
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="path">The path string.</param>
ExpandedSubBlockEnd.gif        
/// <returns><c>true</c> if the path is a UNC path.</returns>

InBlock.gif        public static bool IsUncPath( string path )
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
//  FIRST, check if this is a URL or a UNC path; do this by attempting to construct uri object from it
InBlock.gif
            Uri url = new Uri( path );
InBlock.gif                    
InBlock.gif            
if( url.IsUnc )
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
//  it is a unc path, return true
InBlock.gif
                return true;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return false;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Takes a UNC or URL path, determines which it is (NOT hardened against bad strings, assumes one or the other is present)
InBlock.gif        
/// and returns the path with correct trailing slash: backslash for UNC or
InBlock.gif        
/// slash mark for URL.
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="path">The URL or UNC string.</param>
ExpandedSubBlockEnd.gif        
/// <returns>Path with correct terminal slash.</returns>

InBlock.gif        public static string AppendSlashUrlOrUnc( string path )
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{                    
InBlock.gif            
if( IsUncPath( path ) )
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
//  it is a unc path, so decorate the end with a back-slash (to correct misconfigurations, defend against trivial errors)
InBlock.gif
                return AppendTerminalBackslash( path );
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
//  assume URL here
InBlock.gif
                return AppendTerminalForwardSlash( path );
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// If not present appends terminal backslash to paths.
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="path">A path string; for example, "C:\AppUpdaterClient".</param>
ExpandedSubBlockEnd.gif        
/// <returns>A path string with trailing backslash; for example, "C:\AppUpdaterClient\".</returns>

InBlock.gif        public static string AppendTerminalBackslash( string path )
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if( path.IndexOf( Path.DirectorySeparatorChar, path.Length - 1 ) == -1 )
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return path + Path.DirectorySeparatorChar;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return path;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif        
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Appends a terminal slash mark if there is not already one; returns corrected path.
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="path">The path that may be missing a terminal slash mark.</param>
ExpandedSubBlockEnd.gif        
/// <returns>The corrected path with terminal slash mark.</returns>

InBlock.gif        public static string AppendTerminalForwardSlash( string path )
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
if( path.IndexOf( Path.AltDirectorySeparatorChar, path.Length - 1 ) == -1 )
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return path + Path.AltDirectorySeparatorChar;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
else
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
return path;
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Creates a new temporary folder under the system temp folder
InBlock.gif        
/// and returns its full pathname.
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <returns>The full temp path string.</returns>

InBlock.gif        public static string CreateTemporaryFolder()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return Path.Combine( Path.GetTempPath(), Path.GetFileNameWithoutExtension( Path.GetTempFileName() ) );
ExpandedSubBlockEnd.gif        }

InBlock.gif        
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Copies files from the source to destination directories. Directory.Move is not 
InBlock.gif        
/// suitable here because the downloader may still have the temporary 
InBlock.gif        
/// directory locked. 
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="sourcePath">The source path.</param>
ExpandedSubBlockEnd.gif        
/// <param name="destinationPath">The destination path.</param>

InBlock.gif        public static void CopyDirectory( string sourcePath, string destinationPath )
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            CopyDirectory( sourcePath, destinationPath, 
true );
ExpandedSubBlockEnd.gif        }

InBlock.gif        
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Copies files from the source to destination directories. Directory.Move is not 
InBlock.gif        
/// suitable here because the downloader may still have the temporary 
InBlock.gif        
/// directory locked. 
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="sourcePath">The source path.</param>
InBlock.gif        
/// <param name="destinationPath">The destination path.</param>
ExpandedSubBlockEnd.gif        
/// <param name="overwrite">Indicates whether the destination files should be overwritten.</param>

InBlock.gif        public static void CopyDirectory( string sourcePath, string destinationPath, bool overwrite )
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            CopyDirRecurse( sourcePath, destinationPath, destinationPath, overwrite );
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Move a file from a folder to a new one.
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="existingFileName">The original file name.</param>
InBlock.gif        
/// <param name="newFileName">The new file name.</param>
InBlock.gif        
/// <param name="flags">Flags about how to move the files.</param>
ExpandedSubBlockEnd.gif        
/// <returns>indicates whether the file was moved.</returns>

InBlock.gif        public static bool MoveFile( string existingFileName, string newFileName, MoveFileFlag flags)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
return MoveFileEx( existingFileName, newFileName, (int)flags );
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Deletes a folder. If the folder cannot be deleted at the time this method is called,
InBlock.gif        
/// the deletion operation is delayed until the next system boot.
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <param name="folderPath">The directory to be removed</param>

InBlock.gif        public static void DestroyFolder( string folderPath )
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if ( Directory.Exists( folderPath) )
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    Directory.Delete( folderPath, 
true );
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch( Exception )
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
// If we couldn't remove the files, postpone it to the next system reboot
InBlock.gif
                if ( Directory.Exists( folderPath) )
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    FileUtility.MoveFile(
InBlock.gif                        folderPath,
InBlock.gif                        
null,
InBlock.gif                        MoveFileFlag.DelayUntilReboot );
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Deletes a file. If the file cannot be deleted at the time this method is called,
InBlock.gif        
/// the deletion operation is delayed until the next system boot.
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <param name="filePath">The file to be removed</param>

InBlock.gif        public static void DestroyFile( string filePath )
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if ( File.Exists( filePath ) )
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    File.Delete( filePath );
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if ( File.Exists( filePath ) )
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    FileUtility.MoveFile(
InBlock.gif                        filePath,
InBlock.gif                        
null,
InBlock.gif                        MoveFileFlag.DelayUntilReboot );
ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Clear up a folder. Delete all sub folders and files in the folder.
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <param name="folderPath">The directory to be cleared up</param>

InBlock.gif        public static void ClearUpFolder( string folderPath )
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
// Delete all sub folders
InBlock.gif
            string[] dirs = Directory.GetDirectories( folderPath );
InBlock.gif            
for (int i = 0; i < dirs.Length; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                DestroyFolder( dirs[i] );
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
// Delete all files
InBlock.gif
            string[] files = Directory.GetFiles( folderPath );
InBlock.gif            
for (int i = 0; i < files.Length; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                DestroyFile( files[i] );
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Returns the path to the newer version of the .NET Framework installed on the system.
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <returns>A string containig the full path to the newer .Net Framework location</returns>

InBlock.gif        public static string GetLatestDotNetFrameworkPath()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            Version latestVersion 
= null;
InBlock.gif            
string fwkPath = Path.GetFullPath( Path.Combine( Environment.SystemDirectory, @"..\Microsoft.NET\Framework" ) );
InBlock.gif            
foreach(string path in Directory.GetDirectories( fwkPath, "v*" ) )
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
string candidateVersion = Path.GetFileName( path ).TrimStart( 'v' );
InBlock.gif                
try
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    Version curVersion 
= new Version( candidateVersion );
InBlock.gif                    
if ( latestVersion == null || ( latestVersion != null && latestVersion < curVersion ) )
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        latestVersion 
= curVersion;
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

ExpandedSubBlockStart.gifContractedSubBlock.gif                
catch dot.gif{}
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
return  Path.Combine( fwkPath, "v" + latestVersion.ToString() );
ExpandedSubBlockEnd.gif        }

InBlock.gif
ExpandedSubBlockEnd.gif        
#endregion

InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
Private members#region Private members
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// API declaration of the Win32 function.
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="lpExistingFileName">Existing file path.</param>
InBlock.gif        
/// <param name="lpNewFileName">The file path.</param>
InBlock.gif        
/// <param name="dwFlags">Move file flags.</param>
ExpandedSubBlockEnd.gif        
/// <returns>Whether the file was moved or not.</returns>

InBlock.gif        [DllImport("KERNEL32.DLL")]
InBlock.gif        
private static extern bool MoveFileEx( 
InBlock.gif            
string lpExistingFileName, 
InBlock.gif            
string lpNewFileName, 
InBlock.gif            
long dwFlags );
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// Utility function that recursively copies directories and files.
InBlock.gif        
/// Again, we could use Directory.Move but we need to preserve the original.
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="sourcePath">The source path to copy.</param>
InBlock.gif        
/// <param name="destinationPath">The destination path to copy to.</param>
InBlock.gif        
/// <param name="originalDestination">The original dstination path.</param>
ExpandedSubBlockEnd.gif        
/// <param name="overwrite">Whether the folders should be copied recursively.</param>

InBlock.gif        private static void CopyDirRecurse( string sourcePath, string destinationPath, string originalDestination, bool overwrite )
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
//  ensure terminal backslash
InBlock.gif
            sourcePath = FileUtility.AppendTerminalBackslash( sourcePath );
InBlock.gif            destinationPath 
= FileUtility.AppendTerminalBackslash( destinationPath );
InBlock.gif
InBlock.gif            
if ( !Directory.Exists( destinationPath ) )
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                Directory.CreateDirectory( destinationPath );
ExpandedSubBlockEnd.gif            }

InBlock.gif
InBlock.gif            
//  get dir info which may be file or dir info object
InBlock.gif
            DirectoryInfo dirInfo = new DirectoryInfo( sourcePath );
InBlock.gif
InBlock.gif            
string destFileName = null;
InBlock.gif
InBlock.gif            
foreach( FileSystemInfo fsi in dirInfo.GetFileSystemInfos() )
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
if ( fsi is FileInfo )
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    destFileName 
= Path.Combine( destinationPath, fsi.Name );
InBlock.gif
InBlock.gif                    
//  if file object just copy when overwrite is allowed
InBlock.gif
                    if ( File.Exists( destFileName ) )
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
if ( overwrite )
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            File.Copy( fsi.FullName, destFileName, 
true );
ExpandedSubBlockEnd.gif                        }

ExpandedSubBlockEnd.gif                    }

InBlock.gif                    
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        File.Copy( fsi.FullName, destFileName );
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

InBlock.gif                
else
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
// avoid this recursion path, otherwise copying directories as child directories
InBlock.gif                    
// would be an endless recursion (up to an stack-overflow exception).
InBlock.gif
                    if ( fsi.FullName != originalDestination )
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
//  must be a directory, create destination sub-folder and recurse to copy files
InBlock.gif                        
//Directory.CreateDirectory( destinationPath + fsi.Name );
InBlock.gif
                        CopyDirRecurse( fsi.FullName, destinationPath + fsi.Name, originalDestination, overwrite );
ExpandedSubBlockEnd.gif                    }

ExpandedSubBlockEnd.gif                }

ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockEnd.gif        
#endregion

ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值