File Operation Tools FileUtility (from UABV2.0)

xiaoxiao2021-03-05  32

I have been studying recently

Smart Client's Smart Update development, from

Many things have been learned in Microsoft Updater Application Block v2.0, there is a need to admire

Enterprise Library design, design model and XML application make

Enterprise Library has a strong extension, is very beautiful, it is a good example of learning OOP. After I saw it, I launched my own code to write the code or the process.

.

Enterprise Library advertising is here, the tool class of one of the following operations is from

The original seal in the Microsoft Updater Application Block V2.0 does not move, it feels a certain reference value, I hope to help everyone.

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

// 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 revelementation overview.

//

/ / =========================================================================================================================================================================================== ============================================================================================================================================================================================================= ========== // Copyright? Microsoft Corporation. All Rights Reserved.

// this code and information is provided "as is" without warranty

// of any kind, Either expressed or implied, incruding 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

{

///

/// Indicates how to proceed with the move file operation.

///

[Flags]

Public Enum MoveFileFlag: int

{

///

/// perform a default move funtion.

///

None = 0x0000000000, ///

//////////Iff the Target File Exists, The Move Function Will Replace IT.

///

Replaceexisting = 0x00000001,

///

/// if the file is to be to be moved to a different Volume,

/// The function simulates the move by using the copyfile and deletefile functions.

///

CopyALLOWED = 0x00000002,

///

/// The System Does Not Move The File Until The Operating System Is Restarted.

/// the system moves the file immediately after autochk is Executed, But Before

/// CREANG ANY PAGING FILES. Consesevently, this parameter enables the function

/// to delete Paging Files from previous startups.

///

DelayUntilreboot = 0x00000004,

///

/// The Function Does Not Return Until The File Has Actually Been Moved on The Disk.

///

WriteTHRough = 0x00000008,

///

/// reserved for Future Use.

///

Createhardlink = 0x00000010,

///

////////////// '

///

FailifNottrackable = 0x00000020,

}

///

/// provides Certain Utilities Used by Configuration Processors, Such as Correhensing File paths.

///

Public Sealed Class FileUtility

{

#Region Constructionor

///

/// default constructor.

///

private fileutility ()

{

}

#ndregion

#Region Public MEMBERS

///

/// Returns WHether the path is a unc path.

/// /// The path string.

/// True if the path is a unc path.

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;

}

}

///

/// Takes a UNC OR URL PATH, DETERMINES WHICH IT STRINGS, Assumes One or the Other IS Present

/// and returns the path: BACKSLASH for UNC OR

/// Slash Mark for URL.

///

/// The URL or UNC STRING.

/// Path with Correct Terminal Slash.

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);

}

}

///

/// if Not present appends terminal backslash to patHs.

///

/// a path string; for example, "c: / appupdaterclient".

/// 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;

}

}

///

/// Appends a Terminal Slash Mark if The is not already one; returns corrected path.

///

/// The path this may be missing a Terminal Slash Mark.

/// The Corrected Path with Terminal Slash Mark.

Public Static String appendterminalForwardslash (String Path)

{

IF (path.Indexof (path.altdirectoryseparatorcharchar, path.length - 1) == -1)

{

Return Path path.altdirectoryseparatorchar;

}

Else

{

Return Path;

}

}

///

/// Creates a New Temporary Folder Under The System Temp Folder

/// and return its full pathname.

///

/// The full temp path string.

Public Static String CreateTemportPoraryFolder ()

{

Return path.combine (path.getTemppath (), path.getFileNamewithOUTEXTENSION (Path.getTempFileName ())));

}

///

/// Copies Files from the source to destination Directories. Directory.Move Is Not

/// Suitable Here Because The Downloader May Still Have The Temporary

/// Directory Locked.

///

/// The source path.

/// The destination path.

Public Static Void Copydirectory (String SourcePath, String DestinationPath)

{

CopyDirectory (SourcePath, DestinationPath, True);

}

///

/// Copies Files from the source to destination Directories. Directory.Move Is Not

/// Suitable Here Because The Downloader May Still Have The Temporary

/// Directory Locked.

///

/// The source path. /// The destination path.

/// INDICATES WHETER THE DESTINATION FILES SHOULD BE overwritten.

Public Static Void CopyDirectory (String Sourcepath, String DestinationPath, Bool Overwrite)

{

CopyDirRecurse (SourcePath, DestinationPath, DestinationPath, Overwrite);

}

///

///Move a file from a folder to a new one.

///

/// The Original File Name.

/// The new file name.

/// Flags About how to move the files.

/// INDICATES WHETER THE FILE WAS MOVED.

Public Static Bool Movefile (String NewFileName, String NewFileName, MoveFileflag Flags)

{

Return MovefileEx (ExistingFileName, NewFileName, (int) Flags);

}

///

/// deletes a folder. If the folder cannot be deleted at the time this method is called DETHOD,

/// The deletion Operation is delayed untric the next system boot.

///

/// 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;

}

}

}

///

/// deletes a file. if the file cannot be deleted at the time this method is called,

/// The deletion Operation is delayed untric the next system boot.

///

/// The file to be removed

Public Static Void Destroyfile (String Filepath)

{

Try

{

File.exists (FilePath))

{

File.delete (FilePath);

}

}

Catch

{

File.exists (FilePath))

{

Fileutility.Movefile (

Filepath,

NULL,

Movefileflag.delayuntilreboot;

}

}

}

///

/// Returns the path to the net version of the .net framework installed on the system.

///

/// a string containig the full path to the new .NET Framework location

Public static string getlatestDotNetFrameworkPath ()

{

Version Latestversion = NULL;

String fwkpath = path.getFullPath (path.combine (environment.systemDirectory, @ "../ microsoft.net/framework")));

FOREACH (String Path in Directory.getdirectories))

{

String candidateversion = path.getFileName (PATH) .trimstart ('v');

Try

{

Version Curversion = New Version (CANDIDATEVERSION);

IF (Latestversion == Null || (Latestversion! = Null && Latestversion

{

Latestversion = Curversion;

}

}

Catch {}

}

Return path.combine (fwkpath, "v" Latestversion.toString ());

}

#ndregion

#Region Private MEMBERS

///

/// API Declaration of the win32 function.

///

/// existing file path.

/// The file path. /// Move File Flags.

/// WHETHER THE FILE WAS MOVED or Not.

[DLLIMPORT ("kernel32.dll")]]]]

Private static extern Bool Movefileex

String LpexistingFileName,

String LpnewFileName,

Long dwflags;

///

/// Utility Function That Recursively Copies Directories and FILES.

/// Again, We Could Use Directory.move But We need to preserve the Original.

///

/// The source path to copy.

/// The destination path to copy to.

/// The Original Dstination Path.

/// WHETER THE Folders Should Be copied recursively.

Private Static Void CopyDirRecurse (String SourcePath, 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.com (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);

}

}

}

}

#ndregion

}

}

转载请注明原文地址:https://www.9cbs.com/read-34153.html

New Post(0)