C#文件访问for unity

2015-4-24 雨辰 C#

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using Assets.Scripts.Common.Model;
using Foundation;

namespace Assets.Scripts.Common.Util
{
    /// <summary>
    /// 文件类
    /// </summary>
    public class FileUtil
    {
        /// <summary>
        /// 查找枚举
        /// </summary>
        public enum FindType
        {
            /// <summary>
            /// 文件夹查找
            /// </summary>
            FindDir = 1,

            /// <summary>
            /// 文件查找
            /// </summary>
            FindFile = 2,

            /// <summary>
            /// 查找全部
            /// </summary>
            FileOrDir = 3
        }

        /// <summary>
        /// 获取文件夹中的所有文件列表
        /// </summary>
        /// <param name="directoryPath">文件夹路径</param>
        /// <param name="searchOption">指定是搜索当前目录,还是搜索当前目录及其所有子目录</param>
        /// <param name="search">搜索类型</param>
        /// <returns>所有文件列表</returns>
        public static FileSystemInfo[] GetAllFileSystemInfosInDirectory(string directoryPath, SearchOption searchOption,
            FindType search)
        {
            return GetAllFileSystemInfosInDirectory(new DirectoryInfo(directoryPath), searchOption, search);
        }

        /// <summary>
        /// 获取文件大小
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns></returns>
        public static long GetFileSize(string filePath)
        {
            if (IsFileExists(filePath))
            {
                var fileInfo = new FileInfo(filePath);
                return fileInfo.Length;
            }
            return 0;
        }

        /// <summary>
        /// 获取文件夹中的所有文件列表
        /// </summary>
        /// <param name="directoryInfo">文件夹info</param>
        /// <param name="searchOption">指定是搜索当前目录,还是搜索当前目录及其所有子目录</param>
        /// <param name="search">搜索类型</param>
        /// <returns>所有文件列表</returns>
        public static FileSystemInfo[] GetAllFileSystemInfosInDirectory(DirectoryInfo directoryInfo,
            SearchOption searchOption, FindType search)
        {
            if (search == FindType.FindDir)
            {
                if (directoryInfo != null)
                {
                    try
                    {
                        return directoryInfo.GetDirectories("*", searchOption);
                    }
                    catch (Exception e)
                    {
                        Log.Error(SystemType.Editor, "directory:{0} get directories error, error msg:{1}",
                            directoryInfo.FullName, e.StackTrace);
                    }

                }
            }
            else if (search == FindType.FindFile)
            {
                if (directoryInfo != null)
                {
                    try
                    {
                        return directoryInfo.GetFiles("*.*", searchOption);
                    }
                    catch (Exception e)
                    {
                        Log.Error(SystemType.Editor, "directory:{0} get files error, error msg:{1}",
                            directoryInfo.FullName, e.StackTrace);
                    }
                }
            }

            //查找全部
            if (directoryInfo != null)
            {
                var directories = directoryInfo.GetDirectories("*", searchOption);
                var files = directoryInfo.GetFiles("*.*", searchOption);

                var list = new FileSystemInfo[directories.Length + files.Length];
                var index = 0;

                directories.For(info =>
                {
                    list[index++] = info;
                });

                files.For(info =>
                {
                    list[index++] = info;
                });
                return list;
            }
            return null;
        }

        /// <summary>
        /// 获取文件夹内文件列表
        /// </summary>
        /// <param name="directoryPath">文件夹路径</param>
        /// <param name="searchPattern">指定是搜索当前目录,还是搜索当前目录及其所有子目录</param>
        /// <param name="searchOption">搜索类型</param>
        /// <returns>文件列表</returns>
        public static FileInfo[] GetFileInfosInDirectory(string directoryPath, string searchPattern,
            SearchOption searchOption)
        {
            return GetFileInfosInDirectory(new DirectoryInfo(directoryPath), searchPattern, searchOption);
        }

        /// <summary>
        /// 获取文件夹内文件列表
        /// </summary>
        /// <param name="directoryInfo">文件夹info</param>
        /// <param name="searchPattern">指定是搜索当前目录,还是搜索当前目录及其所有子目录</param>
        /// <param name="searchOption">搜索类型</param>
        /// <returns>文件列表</returns>
        public static FileInfo[] GetFileInfosInDirectory(DirectoryInfo directoryInfo, string searchPattern,
            SearchOption searchOption)
        {
            return directoryInfo.GetFiles(searchPattern, searchOption);
        }

        /// <summary>
        /// 文件夹是否存在
        /// </summary>
        /// <param name="directoryPath"></param>
        /// <returns></returns>
        public static bool IsDirectoryExists(string directoryPath)
        {
            return Directory.Exists(directoryPath);
        }

        /// <summary>
        /// 创建文件夹
        /// </summary>
        /// <param name="directoryPath">文件夹路径</param>
        public static void CreateDirectory(string directoryPath)
        {
            if (!Directory.Exists(directoryPath))
                Directory.CreateDirectory(directoryPath);
        }

        /// <summary>
        /// 删除文件夹
        /// </summary>
        /// <param name="directoryPath">文件夹路径</param>
        public static void DeleteDirectory(string directoryPath)
        {
            if (Directory.Exists(directoryPath))
            {
                try
                {
                    Directory.Delete(directoryPath, true);
                }
                catch (Exception exception)
                {
                    Log.Error(string.Format("删除{0}目录失败:{1}", directoryPath, exception.Message));
                }
            }
        }

        /// <summary>
        /// 重现创建文件夹
        /// </summary>
        /// <param name="directoryPath">文件夹路径</param>
        public static void RecreateDirectory(string directoryPath)
        {
            if (Directory.Exists(directoryPath))
            {
                Directory.Delete(directoryPath, true);
            }
            Directory.CreateDirectory(directoryPath);
        }

        /// <summary>
        /// 复制文件夹及所有子文件
        /// </summary>
        /// <param name="srcPath">源路径</param>
        /// <param name="destPath">目标路径</param>
        /// <param name="includeExtensions">只拷贝包括的文件类型</param>
        /// <param name="ignoreExtensions">忽略的文件类型</param>
        /// <param name="isOverwrite">是否重写</param>
        public static void CopyDirectory(string srcPath, string destPath, string[] includeExtensions = null, string[] ignoreExtensions = null, bool isOverwrite = true)
        {
            CopyAllIncludeFileAndDirectory(srcPath, destPath, includeExtensions, ignoreExtensions, isOverwrite, false);
        }

        /// <summary>
        /// 移动文件夹及所有子文件
        /// </summary>
        /// <param name="srcPath">源路径</param>
        /// <param name="destPath">目标路径</param>
        /// <param name="isOverwrite">是否重写</param>
        public static void MoveDirectory(string srcPath, string destPath, bool isOverwrite = true)
        {
            CopyAllIncludeFileAndDirectory(srcPath, destPath, null, null, isOverwrite, true);
            DeleteDirectory(srcPath);
        }

        /// <summary>
        /// 复制
        /// </summary>
        /// <param name="srcPath">源路径</param>
        /// <param name="destPath">目标路径</param>
        /// <param name="includeExtensions">只拷贝包括的文件类型</param>
        /// <param name="ignoreExtensions">忽略的文件类型</param>
        /// <param name="isOverwrite">是否重写</param>
        /// <param name="isDeleteSource">是否删除源文件</param>
        private static void CopyAllIncludeFileAndDirectory(string srcPath, string destPath, string[] includeExtensions, string[] ignoreExtensions, bool isOverwrite, bool isDeleteSource)
        {
            if (!Directory.Exists(srcPath))
            {
                Log.Error(string.Format("{0} is not exists", srcPath));
                return;
            }
            var info = new DirectoryInfo(srcPath);
            if (!Directory.Exists(destPath))
                Directory.CreateDirectory(destPath);
            info.GetFileSystemInfos().For(fsi =>
            {
                var destName = Path.Combine(destPath, fsi.Name);

                if (fsi is FileInfo)
                {
                    //如果是文件,复制文件
                    if ((includeExtensions == null || (!string.IsNullOrEmpty(fsi.Extension) && Array.IndexOf(includeExtensions, fsi.Extension) >= 0)) &&
                        (ignoreExtensions == null || string.IsNullOrEmpty(fsi.Extension) || Array.IndexOf(ignoreExtensions, fsi.Extension) < 0))
                    {
                        File.Copy(fsi.FullName, destName, isOverwrite);
                        if (isDeleteSource)
                        {
                            try
                            {
                                File.Delete(fsi.FullName);
                            }
                            catch (Exception exception)
                            {
                                Log.Error(string.Format("CopyAllIncludeFileAndDirectory 删除{0}文件错误:{1}", fsi.FullName, exception.Message));
                            }
                        }
                    }
                }
                else
                {
                    //如果是文件夹,新建文件夹,递归
                    Directory.CreateDirectory(destName);
                    CopyAllIncludeFileAndDirectory(fsi.FullName, destName, includeExtensions, ignoreExtensions, isOverwrite, isDeleteSource);
                }
            });
        }

        /// <summary>
        /// 文件是否存在
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>yes or no</returns>
        public static bool IsFileExists(string filePath)
        {
            return File.Exists(filePath);
        }

        /// <summary>
        /// 根据文件扩展名删除指定目录下所有的文件。
        /// </summary>
        /// <param name="dir">指定目录</param>
        /// <param name="extension">扩展名(支持*.txt,txt,.txt均可)</param>
        public static void DeleteAllFilesByExtension(string dir, string extension)
        {
            if (!Directory.Exists(dir))
                return;

            if (!extension.Contains("*"))
            {
                if (extension.Contains("."))
                {
                    extension = "*" + extension;
                }
                else
                {
                    extension = "*." + extension;
                }
            }

            DirectoryInfo di = new DirectoryInfo(dir);
            var shortExtension = extension.Replace("*", "");
            FileInfo[] files = di.GetFiles(extension, SearchOption.AllDirectories).Where(p => p.Extension.ToLower().Equals(shortExtension.ToLower())).ToArray();
            for (int i = 0; i < files.Length; i++)
            {
                var file = files[i];
                file.Attributes = FileAttributes.Normal;
                File.Delete(file.FullName);
            }
        }

        /// <summary>
        /// 删除文件
        /// </summary>
        /// <param name="filePath">文件路径</param>
        public static void DeleteFile(string filePath)
        {
            if (IsFileExists(filePath))
            {
                File.Delete(filePath);
            }
        }

        /// <summary>
        /// 拷贝文件
        /// </summary>
        /// <param name="srcPath">源路径</param>
        /// <param name="destPath">目标路径</param>
        public static void CopyFile(string srcPath, string destPath)
        {
            if (!File.Exists(srcPath))
            {
                Log.Error(string.Format("{0} is not exists", srcPath));
                return;
            }

            var destFolder = Path.GetDirectoryName(destPath);
            if (!Directory.Exists(destFolder))
                Directory.CreateDirectory(destFolder);
            var fi = new FileInfo(srcPath);
            File.Copy(fi.FullName, destPath, true);
        }

        /// <summary>
        /// 快速拷贝
        /// </summary>
        /// <param name="srcPath"></param>
        /// <param name="destPath"></param>
        public static void QuickCopyFile(string srcPath, string destPath)
        {
            if (srcPath == "" || destPath == "")
            {
                return;
            }

            var fi = new FileInfo(srcPath);
            File.Copy(fi.FullName, destPath, true);
        }

        /// <summary>
        /// 获取文件名
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="isNeedExtension">是否需要扩展名</param>
        /// <returns>文件名</returns>
        public static string GetFileNameWithoutExt(string filePath, bool isNeedExtension)
        {
            return GetFileNameWithoutExt(new FileInfo(filePath), isNeedExtension);
        }

        /// <summary>
        /// 获取文件名
        /// </summary>
        /// <param name="fileInfo">文件info</param>
        /// <param name="isNeedExtension">是否需要扩展名</param>
        /// <returns>文件名</returns>
        public static string GetFileNameWithoutExt(FileInfo fileInfo, bool isNeedExtension)
        {
            if (isNeedExtension)
                return fileInfo.Name;
            return fileInfo.Name.Substring(0, fileInfo.Name.LastIndexOf('.'));
        }

        /// <summary>
        /// 获取文件扩展名
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>扩展名</returns>
        public static string GetFileExt(string filePath)
        {
            return GetFileExt(new FileInfo(filePath));
        }

        /// <summary>
        /// 获取文件扩展名
        /// </summary>
        /// <param name="info">文件info</param>
        /// <returns>扩展名</returns>
        public static string GetFileExt(FileInfo info)
        {
            return info.Extension.Substring(1);
        }

        /// <summary>
        /// 更改文件名
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <param name="newFileName">新文件名</param>
        public static void ModifyFileName(string filePath, string newFileName)
        {
            var parent = filePath.Substring(0, filePath.LastIndexOf("/"));
            var bytes = ReadFileToBytes(filePath);
            if (bytes != null)
            {
                WriteBytesToFile(bytes, parent + "/" + newFileName);
                DeleteFile(filePath);
            }
        }

        /// <summary>
        /// 获取父目录路径
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>父目录路径</returns>
        public static string GetFileParentDirectoryPath(string filePath)
        {
            return new FileInfo(filePath).DirectoryName;
        }

        /// <summary>
        /// 创建父目录
        /// </summary>
        /// <param name="filePath">文件路径</param>
        public static void CreateParentDirectory(string filePath)
        {
            var parentFolderName = new FileInfo(filePath).DirectoryName;
            if (parentFolderName != null && !Directory.Exists(parentFolderName))
                Directory.CreateDirectory(parentFolderName);
        }

        /// <summary>
        /// 打开txt文本,并返回内容
        /// </summary>
        /// <param name="txtFilePath">文本路径</param>
        /// <param name="encoding">编码格式</param>
        /// <returns>文本内容</returns>
        public static string ReadTxtFile(string txtFilePath, Encoding encoding = null)
        {
            if (File.Exists(txtFilePath))
            {
                using (var fs = new FileStream(txtFilePath, FileMode.Open, FileAccess.Read))
                {
                    using (var sr = new StreamReader(fs, encoding ?? Encoding.UTF8))
                    {
                        return sr.ReadToEnd();
                    }
                }
            }
            return string.Empty;
        }

        /// <summary>
        /// 写入txt文件
        /// </summary>
        /// <param name="txt">写入内容</param>
        /// <param name="filePath">文件路径</param>
        /// <param name="encoding">编码格式</param>
        public static void WriteTxtToFile(string txt, string filePath, Encoding encoding = null)
        {
            try
            {
                CreateParentDirectory(filePath);
                using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                {
                    if (encoding == null)
                    {
                        encoding = new UTF8Encoding();
                    }
                    var bytes = encoding.GetBytes(txt);
                    fileStream.Write(bytes, 0, bytes.Length);
                    fileStream.Flush();
                    fileStream.Close();
                }
            }
            catch (Exception arg)
            {
                Log.Error("写入文件失败" + arg);
            }
        }

        /// <summary>
        /// 增加文本内容
        /// </summary>
        /// <param name="txt">需增加的内容</param>
        /// <param name="filePath">文件路径</param>
        public static void AppendTxtToFile(string txt, string filePath)
        {
            try
            {
                //如果要写入的目录不存在
                CreateParentDirectory(filePath);
                using (var fs = new FileStream(filePath, FileMode.Append, FileAccess.Write))
                {
                    var data = new UTF8Encoding().GetBytes(txt);
                    fs.Write(data, 0, data.Length);
                    fs.Flush();
                    fs.Close();
                }
            }
            catch (Exception e)
            {
                Log.Error("AppendTxtToFile失败 " + txt + "  " + e);
            }
        }

        /// <summary>
        /// 打开xml文件
        /// </summary>
        /// <param name="xmlFilePath">xml文件路径</param>
        /// <returns>xml文档</returns>
        public static XmlDocument ReadXmlFile(string xmlFilePath)
        {
            XmlDocument xml = null;
            if (File.Exists(xmlFilePath))
            {
                using (var fs = new FileStream(xmlFilePath, FileMode.Open, FileAccess.Read))
                {
                    using (var sr = new StreamReader(fs))
                    {
                        xml = new XmlDocument();
                        xml.Load(sr);
                    }
                }
            }
            return xml;
        }

        /// <summary>
        /// 写入xml文件
        /// </summary>
        /// <param name="xmlDocument">xml文档</param>
        /// <param name="filePath">文件路径</param>
        public static void WriteXmlFile(XmlDocument xmlDocument, string filePath)
        {
            //如果要写入的目录不存在
            CreateParentDirectory(filePath);
            using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
            {
                using (var sw = new StreamWriter(fs, new UTF8Encoding(true, true)))
                {
                    xmlDocument.Save(sw);
                }
            }
        }

        /// <summary>
        /// 打开文件返回数据
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>返回数据</returns>
        public static byte[] ReadFileToBytes(string filePath)
        {
            byte[] bytes = null;
            if (File.Exists(filePath))
            {
                using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    using (var br = new BinaryReader(fs))
                    {
                        bytes = new byte[fs.Length];
                        br.Read(bytes, 0, bytes.Length);
                    }
                }
            }
            return bytes;
        }

        /// <summary>
        /// 打开文件返回数据
        /// </summary>
        /// <param name="filePath">文件路径</param>
        /// <returns>返回数据</returns>
        public static byte[] Rename(string filePath)
        {
            byte[] bytes = null;
            if (File.Exists(filePath))
            {
                using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    using (var br = new BinaryReader(fs))
                    {
                        bytes = new byte[fs.Length];
                        br.Read(bytes, 0, bytes.Length);
                    }
                }
            }
            return bytes;
        }

        /// <summary>
        /// 写入文件
        /// </summary>
        /// <param name="bytes">数据</param>
        /// <param name="filePath">文件路径</param>
        public static void WriteBytesToFile(byte[] bytes, string filePath)
        {
            //如果要写入的目录不存在
            CreateParentDirectory(filePath);
            try
            {
                using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
                {
                    using (var binaryWriter = new BinaryWriter(fileStream))
                    {
                        binaryWriter.Write(bytes);
                    }
                }
            }
            catch (IOException ex)
            {
                Log.Error("WriteBytesToFile", ex.Message);
            }
        }

        //    /// <returns>返回数据</returns>
        //    /// <param name="gzipBytes">压缩数据</param>
        //    /// </summary>
        //    /// 打开zip压缩数据

        //    /// <summary>
        //    }
        //        return re.ToArray();
        //        }
        //            }
        //                }
        //                    }
        //                        re.Write(data, 0, count);
        //                    {
        //                    while ((count = input.Read(data, 0, data.Length)) != 0)
        //                    int count = 0;
        //                    byte[] data = new byte[4096];
        //                {
        //                using (GZipInputStream input = new GZipInputStream(fs))
        //            {
        //            using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        //        {
        //        if (File.Exists(filePath))
        //        MemoryStream re = new MemoryStream();
        //    {
        //    public static byte[] ReadGZipFile(string filePath)
        //    /// <returns>返回数据</returns>
        //    /// <param name="filePath">文件路径</param>
        //    /// </summary>
        //    /// 打开zip压缩文件

        //    /// <summary>
        //    public static byte[] ReadGZipBytes(byte[] gzipBytes)
        //    {
        //        MemoryStream re = new MemoryStream();
        //        using (MemoryStream ms = new MemoryStream(gzipBytes))
        //        {
        //            using (GZipInputStream input = new GZipInputStream(ms))
        //            {
        //                byte[] data = new byte[4096];
        //                int count = 0;
        //                while ((count = input.Read(data, 0, data.Length)) > 0)
        //                {
        //                    re.Write(data, 0, count);
        //                }
        //            }
        //        }
        //        return re.ToArray();
        //    }


        //    /// <summary>
        //    /// 压缩文件zip
        //    /// </summary>
        //    /// <param name="bytes">数据</param>
        //    /// <param name="filePath">文件路径</param>
        //    public static void WriteGzipFile(byte[] bytes, string filePath)
        //    {
        //        CreateParentDirectory(filePath);
        //        using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
        //        {
        //            using (GZipOutputStream gzip = new GZipOutputStream(fs))
        //            {
        //                gzip.Write(bytes, 0, bytes.Length);
        //            }
        //        }
        //    }
    }
}

标签: C#

发表评论:

雨辰 joyimp|@2011-2018 京ICP备16030765号