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

2024-02-17 10:58

本文主要是介绍文件操作工具类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

{

    /// <summary>

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

    /// </summary>

    [Flags]

    public enum MoveFileFlag : int

    {

        /// <summary>

        /// Perform a default move funtion.

        /// </summary>

        None                = 0x00000000,

        /// <summary>

        /// If the target file exists, the move function will replace it.

        /// </summary>

        ReplaceExisting     = 0x00000001,

        /// <summary>

        /// If the file is to be moved to a different volume,

        /// the function simulates the move by using the CopyFile and DeleteFile functions.

        /// </summary>

        CopyAllowed         = 0x00000002,

        /// <summary>

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

        /// creating any paging files. Consequently, this parameter enables the function

        /// to delete paging files from previous startups.

        /// </summary>

        DelayUntilReboot    = 0x00000004,

        /// <summary>

        /// The function does not return until the file has actually been moved on the disk.

        /// </summary>

        WriteThrough        = 0x00000008,

        /// <summary>

        /// Reserved for future use.

        /// </summary>

        CreateHardLink      = 0x00000010,

        /// <summary>

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

        /// </summary>

        FailIfNotTrackable  = 0x00000020,

    }

 

    /// <summary>

    /// Provides certain utilities used by configuration processors, such as correcting file paths.

    /// </summary>

    public sealed class FileUtility

    {

        #region Constructor

 

        /// <summary>

        /// Default constructor.

        /// </summary>

        private FileUtility()

        {

        }

 

        #endregion

 

        #region Public members

 

        /// <summary>

        /// Returns whether the path is a UNC path.

        /// </summary>

        /// <param name="path">The path string.</param>

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

            }

        }

 

        /// <summary>

        /// Takes a UNC or URL path, determines which it is (NOT hardened against bad strings, assumes one or the other is present)

        /// and returns the path with correct trailing slash: backslash for UNC or

        /// slash mark for URL.

        /// </summary>

        /// <param name="path">The URL or UNC string.</param>

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

            }

        }

 

        /// <summary>

        /// If not present appends terminal backslash to paths.

        /// </summary>

        /// <param name="path">A path string; for example, "C:/AppUpdaterClient".</param>

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

            }

        }

       

        /// <summary>

        /// Appends a terminal slash mark if there is not already one; returns corrected path.

        /// </summary>

        /// <param name="path">The path that may be missing a terminal slash mark.</param>

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

            }

        }

 

        /// <summary>

        /// Creates a new temporary folder under the system temp folder

        /// and returns its full pathname.

        /// </summary>

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

        public static string CreateTemporaryFolder()

        {

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

        }

        

        /// <summary>

        /// Copies files from the source to destination directories. Directory.Move is not

        /// suitable here because the downloader may still have the temporary

        /// directory locked.

        /// </summary>

        /// <param name="sourcePath">The source path.</param>

        /// <param name="destinationPath">The destination path.</param>

        public static void CopyDirectory( string sourcePath, string destinationPath )

        {

            CopyDirectory( sourcePath, destinationPath, true );

        }

       

        /// <summary>

        /// Copies files from the source to destination directories. Directory.Move is not

        /// suitable here because the downloader may still have the temporary

        /// directory locked.

        /// </summary>

        /// <param name="sourcePath">The source path.</param>

        /// <param name="destinationPath">The destination path.</param>

        /// <param name="overwrite">Indicates whether the destination files should be overwritten.</param>

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

        {

            CopyDirRecurse( sourcePath, destinationPath, destinationPath, overwrite );

        }

 

        /// <summary>

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

        /// </summary>

        /// <param name="existingFileName">The original file name.</param>

        /// <param name="newFileName">The new file name.</param>

        /// <param name="flags">Flags about how to move the files.</param>

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

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

        {

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

        }

 

        /// <summary>

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

        /// the deletion operation is delayed until the next system boot.

        /// </summary>

        /// <param name="folderPath">The directory to be removed</param>

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

                }

            }

        }

 

        /// <summary>

        /// Deletes a file. If the file cannot be deleted at the time this method is called,

        /// the deletion operation is delayed until the next system boot.

        /// </summary>

        /// <param name="filePath">The file to be removed</param>

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

                }

            }

        }

 

 

        /// <summary>

        /// Returns the path to the newer version of the .NET Framework installed on the system.

        /// </summary>

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

 

        /// <summary>

        /// API declaration of the Win32 function.

        /// </summary>

        /// <param name="lpExistingFileName">Existing file path.</param>

        /// <param name="lpNewFileName">The file path.</param>

        /// <param name="dwFlags">Move file flags.</param>

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

        [DllImport("KERNEL32.DLL")]

        private static extern bool MoveFileEx(

            string lpExistingFileName,

            string lpNewFileName,

            long dwFlags );

 

        /// <summary>

        /// Utility function that recursively copies directories and files.

        /// Again, we could use Directory.Move but we need to preserve the original.

        /// </summary>

        /// <param name="sourcePath">The source path to copy.</param>

        /// <param name="destinationPath">The destination path to copy to.</param>

        /// <param name="originalDestination">The original dstination path.</param>

        /// <param name="overwrite">Whether the folders should be copied recursively.</param>

        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

    }

}

这篇关于文件操作工具类FileUtility(摘自UABv2.0)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/717567

相关文章

使用MongoDB进行数据存储的操作流程

《使用MongoDB进行数据存储的操作流程》在现代应用开发中,数据存储是一个至关重要的部分,随着数据量的增大和复杂性的增加,传统的关系型数据库有时难以应对高并发和大数据量的处理需求,MongoDB作为... 目录什么是MongoDB?MongoDB的优势使用MongoDB进行数据存储1. 安装MongoDB

Linux使用fdisk进行磁盘的相关操作

《Linux使用fdisk进行磁盘的相关操作》fdisk命令是Linux中用于管理磁盘分区的强大文本实用程序,这篇文章主要为大家详细介绍了如何使用fdisk进行磁盘的相关操作,需要的可以了解下... 目录简介基本语法示例用法列出所有分区查看指定磁盘的区分管理指定的磁盘进入交互式模式创建一个新的分区删除一个存

Golang操作DuckDB实战案例分享

《Golang操作DuckDB实战案例分享》DuckDB是一个嵌入式SQL数据库引擎,它与众所周知的SQLite非常相似,但它是为olap风格的工作负载设计的,DuckDB支持各种数据类型和SQL特性... 目录DuckDB的主要优点环境准备初始化表和数据查询单行或多行错误处理和事务完整代码最后总结Duck

基于Python开发电脑定时关机工具

《基于Python开发电脑定时关机工具》这篇文章主要为大家详细介绍了如何基于Python开发一个电脑定时关机工具,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录1. 简介2. 运行效果3. 相关源码1. 简介这个程序就像一个“忠实的管家”,帮你按时关掉电脑,而且全程不需要你多做

C# 读写ini文件操作实现

《C#读写ini文件操作实现》本文主要介绍了C#读写ini文件操作实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录一、INI文件结构二、读取INI文件中的数据在C#应用程序中,常将INI文件作为配置文件,用于存储应用程序的

Python使用qrcode库实现生成二维码的操作指南

《Python使用qrcode库实现生成二维码的操作指南》二维码是一种广泛使用的二维条码,因其高效的数据存储能力和易于扫描的特点,广泛应用于支付、身份验证、营销推广等领域,Pythonqrcode库是... 目录一、安装 python qrcode 库二、基本使用方法1. 生成简单二维码2. 生成带 Log

Java操作ElasticSearch的实例详解

《Java操作ElasticSearch的实例详解》Elasticsearch是一个分布式的搜索和分析引擎,广泛用于全文搜索、日志分析等场景,本文将介绍如何在Java应用中使用Elastics... 目录简介环境准备1. 安装 Elasticsearch2. 添加依赖连接 Elasticsearch1. 创

基于C#实现PDF文件合并工具

《基于C#实现PDF文件合并工具》这篇文章主要为大家详细介绍了如何基于C#实现一个简单的PDF文件合并工具,文中的示例代码简洁易懂,有需要的小伙伴可以跟随小编一起学习一下... 界面主要用于发票PDF文件的合并。经常出差要报销的很有用。代码using System;using System.Col

redis-cli命令行工具的使用小结

《redis-cli命令行工具的使用小结》redis-cli是Redis的命令行客户端,支持多种参数用于连接、操作和管理Redis数据库,本文给大家介绍redis-cli命令行工具的使用小结,感兴趣的... 目录基本连接参数基本连接方式连接远程服务器带密码连接操作与格式参数-r参数重复执行命令-i参数指定命

java Stream操作转换方法

《javaStream操作转换方法》文章总结了Java8中流(Stream)API的多种常用方法,包括创建流、过滤、遍历、分组、排序、去重、查找、匹配、转换、归约、打印日志、最大最小值、统计、连接、... 目录流创建1、list 转 map2、filter()过滤3、foreach遍历4、groupingB