文件操作工具类FileUtility(摘自UABv2.0)

最近一直在研究 Smart Client 的 Smart Update 开发,从 Microsoft Updater Application Block v2.0 里面学到了很多东西,这里不得不佩服 Enterprise Library 的设计,设计模式和 XML 的运用使得 Enterprise Library 的扩展性很强,设计十分优美,是学习 OOP 的好范例。本人看了之后感叹自己写的代码大部分还是面向过程

Enterprise Library 的广告就做到这里了,下面一个操作文件的工具类是从 Microsoft Updater Application Block v2.0 里面原封不动取出来,感觉具有一定的参考价值,希望对大家有帮助。

//============================================================================================================

// Microsoft Updater Application Block for .NET

// http://msdn.microsoft.com/library/en-us/dnbda/html/updater.asp

//

// FileUtility.cs

//

// Contains the implementation of the FileUtility helper class.

//

// For more information see the Updater Application Block Implementation Overview.

//

//============================================================================================================

// Copyright ?Microsoft Corporation. All rights reserved.

// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY

// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT

// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND

// FITNESS FOR A PARTICULAR PURPOSE.

//============================================================================================================

using System;

using System.IO;

using System.Runtime.InteropServices;

namespace Microsoft.ApplicationBlocks.Updater.Utilities

{

///

1<summary>
2
3/// Indicates how to proceed with the move file operation. 
4
5/// </summary>

[Flags]

public enum MoveFileFlag : int

{

///

1<summary>
2
3/// Perform a default move funtion. 
4
5/// </summary>

None = 0x00000000,

///

1<summary>
2
3/// If the target file exists, the move function will replace it. 
4
5/// </summary>

ReplaceExisting = 0x00000001,

///

1<summary>
2
3/// If the file is to be moved to a different volume, 
4
5/// the function simulates the move by using the CopyFile and DeleteFile functions. 
6
7/// </summary>

CopyAllowed = 0x00000002,

///

 1<summary>
 2
 3/// The system does not move the file until the operating system is restarted. 
 4
 5/// The system moves the file immediately after AUTOCHK is executed, but before 
 6
 7/// creating any paging files. Consequently, this parameter enables the function 
 8
 9/// to delete paging files from previous startups. 
10
11/// </summary>

DelayUntilReboot = 0x00000004,

///

1<summary>
2
3/// The function does not return until the file has actually been moved on the disk. 
4
5/// </summary>

WriteThrough = 0x00000008,

///

1<summary>
2
3/// Reserved for future use. 
4
5/// </summary>

CreateHardLink = 0x00000010,

///

1<summary>
2
3/// 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. 
4
5/// </summary>

FailIfNotTrackable = 0x00000020,

}

///

1<summary>
2
3/// Provides certain utilities used by configuration processors, such as correcting file paths. 
4
5/// </summary>

public sealed class FileUtility

{

#region Constructor

///

1<summary>
2
3/// Default constructor. 
4
5/// </summary>

private FileUtility()

{

}

#endregion

#region Public members

///

1<summary>
2
3/// Returns whether the path is a UNC path. 
4
5/// </summary>

///

1<param name="path"/>

The path string.

///

1<returns><c>true</c> if the path is a UNC path.</returns>

public static bool IsUncPath( string path )

{

// FIRST, check if this is a URL or a UNC path; do this by attempting to construct uri object from it

Uri url = new Uri( path );

if( url.IsUnc )

{

// it is a unc path, return true

return true;

}

else

{

return false;

}

}

///

1<summary>
2
3/// Takes a UNC or URL path, determines which it is (NOT hardened against bad strings, assumes one or the other is present) 
4
5/// and returns the path with correct trailing slash: backslash for UNC or 
6
7/// slash mark for URL. 
8
9/// </summary>

///

1<param name="path"/>

The URL or UNC string.

///

1<returns>Path with correct terminal slash.</returns>

public static string AppendSlashUrlOrUnc( string path )

{

if( IsUncPath( path ) )

{

// it is a unc path, so decorate the end with a back-slash (to correct misconfigurations, defend against trivial errors)

return AppendTerminalBackslash( path );

}

else

{

// assume URL here

return AppendTerminalForwardSlash( path );

}

}

///

1<summary>
2
3/// If not present appends terminal backslash to paths. 
4
5/// </summary>

///

1<param name="path"/>

A path string; for example, "C:\AppUpdaterClient".

///

1<returns>A path string with trailing backslash; for example, "C:\AppUpdaterClient\".</returns>

public static string AppendTerminalBackslash( string path )

{

if( path.IndexOf( Path.DirectorySeparatorChar, path.Length - 1 ) == -1 )

{

return path + Path.DirectorySeparatorChar;

}

else

{

return path;

}

}

///

1<summary>
2
3/// Appends a terminal slash mark if there is not already one; returns corrected path. 
4
5/// </summary>

///

1<param name="path"/>

The path that may be missing a terminal slash mark.

///

1<returns>The corrected path with terminal slash mark.</returns>

public static string AppendTerminalForwardSlash( string path )

{

if( path.IndexOf( Path.AltDirectorySeparatorChar, path.Length - 1 ) == -1 )

{

return path + Path.AltDirectorySeparatorChar;

}

else

{

return path;

}

}

///

1<summary>
2
3/// Creates a new temporary folder under the system temp folder 
4
5/// and returns its full pathname. 
6
7/// </summary>

///

1<returns>The full temp path string.</returns>

public static string CreateTemporaryFolder()

{

return Path.Combine( Path.GetTempPath(), Path.GetFileNameWithoutExtension( Path.GetTempFileName() ) );

}

///

1<summary>
2
3/// Copies files from the source to destination directories. Directory.Move is not 
4
5/// suitable here because the downloader may still have the temporary 
6
7/// directory locked. 
8
9/// </summary>

///

1<param name="sourcePath"/>

The source path.

///

1<param name="destinationPath"/>

The destination path.

public static void CopyDirectory( string sourcePath, string destinationPath )

{

CopyDirectory( sourcePath, destinationPath, true );

}

///

1<summary>
2
3/// Copies files from the source to destination directories. Directory.Move is not 
4
5/// suitable here because the downloader may still have the temporary 
6
7/// directory locked. 
8
9/// </summary>

///

1<param name="sourcePath"/>

The source path.

///

1<param name="destinationPath"/>

The destination path.

///

1<param name="overwrite"/>

Indicates whether the destination files should be overwritten.

public static void CopyDirectory( string sourcePath, string destinationPath, bool overwrite )

{

CopyDirRecurse( sourcePath, destinationPath, destinationPath, overwrite );

}

///

1<summary>
2
3/// Move a file from a folder to a new one. 
4
5/// </summary>

///

1<param name="existingFileName"/>

The original file name.

///

1<param name="newFileName"/>

The new file name.

///

1<param name="flags"/>

Flags about how to move the files.

///

1<returns>indicates whether the file was moved.</returns>

public static bool MoveFile( string existingFileName, string newFileName, MoveFileFlag flags)

{

return MoveFileEx( existingFileName, newFileName, (int)flags );

}

///

1<summary>
2
3/// Deletes a folder. If the folder cannot be deleted at the time this method is called, 
4
5/// the deletion operation is delayed until the next system boot. 
6
7/// </summary>

///

1<param name="folderPath"/>

The directory to be removed

public static void DestroyFolder( string folderPath )

{

try

{

if ( Directory.Exists( folderPath) )

{

Directory.Delete( folderPath, true );

}

}

catch( Exception )

{

// If we couldn't remove the files, postpone it to the next system reboot

if ( Directory.Exists( folderPath) )

{

FileUtility.MoveFile(

folderPath,

null,

MoveFileFlag.DelayUntilReboot );

}

}

}

///

1<summary>
2
3/// Deletes a file. If the file cannot be deleted at the time this method is called, 
4
5/// the deletion operation is delayed until the next system boot. 
6
7/// </summary>

///

1<param name="filePath"/>

The file to be removed

public static void DestroyFile( string filePath )

{

try

{

if ( File.Exists( filePath ) )

{

File.Delete( filePath );

}

}

catch

{

if ( File.Exists( filePath ) )

{

FileUtility.MoveFile(

filePath,

null,

MoveFileFlag.DelayUntilReboot );

}

}

}

///

1<summary>
2
3/// Returns the path to the newer version of the .NET Framework installed on the system. 
4
5/// </summary>

///

1<returns>A string containig the full path to the newer .Net Framework location</returns>

public static string GetLatestDotNetFrameworkPath()

{

Version latestVersion = null;

string fwkPath = Path.GetFullPath( Path.Combine( Environment.SystemDirectory, @"..\Microsoft.NET\Framework" ) );

foreach(string path in Directory.GetDirectories( fwkPath, "v*" ) )

{

string candidateVersion = Path.GetFileName( path ).TrimStart( 'v' );

try

{

Version curVersion = new Version( candidateVersion );

if ( latestVersion == null || ( latestVersion != null && latestVersion < curVersion ) )

{

latestVersion = curVersion;

}

}

catch {}

}

return Path.Combine( fwkPath, "v" + latestVersion.ToString() );

}

#endregion

#region Private members

///

1<summary>
2
3/// API declaration of the Win32 function. 
4
5/// </summary>

///

1<param name="lpExistingFileName"/>

Existing file path.

///

1<param name="lpNewFileName"/>

The file path.

///

1<param name="dwFlags"/>

Move file flags.

///

1<returns>Whether the file was moved or not.</returns>

[DllImport("KERNEL32.DLL")]

private static extern bool MoveFileEx(

string lpExistingFileName,

string lpNewFileName,

long dwFlags );

///

1<summary>
2
3/// Utility function that recursively copies directories and files. 
4
5/// Again, we could use Directory.Move but we need to preserve the original. 
6
7/// </summary>

///

1<param name="sourcePath"/>

The source path to copy.

///

1<param name="destinationPath"/>

The destination path to copy to.

///

1<param name="originalDestination"/>

The original dstination path.

///

1<param name="overwrite"/>

Whether the folders should be copied recursively.

private static void CopyDirRecurse( string sourcePath, string destinationPath, string originalDestination, bool overwrite )

{

// ensure terminal backslash

sourcePath = FileUtility.AppendTerminalBackslash( sourcePath );

destinationPath = FileUtility.AppendTerminalBackslash( destinationPath );

if ( !Directory.Exists( destinationPath ) )

{

Directory.CreateDirectory( destinationPath );

}

// get dir info which may be file or dir info object

DirectoryInfo dirInfo = new DirectoryInfo( sourcePath );

string destFileName = null;

foreach( FileSystemInfo fsi in dirInfo.GetFileSystemInfos() )

{

if ( fsi is FileInfo )

{

destFileName = Path.Combine( destinationPath, fsi.Name );

// if file object just copy when overwrite is allowed

if ( File.Exists( destFileName ) )

{

if ( overwrite )

{

File.Copy( fsi.FullName, destFileName, true );

}

}

else

{

File.Copy( fsi.FullName, destFileName );

}

}

else

{

// avoid this recursion path, otherwise copying directories as child directories

// would be an endless recursion (up to an stack-overflow exception).

if ( fsi.FullName != originalDestination )

{

// must be a directory, create destination sub-folder and recurse to copy files

//Directory.CreateDirectory( destinationPath + fsi.Name );

CopyDirRecurse( fsi.FullName, destinationPath + fsi.Name, originalDestination, overwrite );

}

}

}

}

#endregion

}

}

Published At
Categories with Web编程
Tagged with
comments powered by Disqus