C# 文件读写辅助类

分类:C#     发布:2019-08-09     来源:本站     浏览:746 次
//--------------------------------------------------------------------------------
// 文件描述:文件读写辅助类
// 文件作者:全体开发人员 
//--------------------------------------------------------------------------------

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;

namespace RC.Framework
{
    /// <summary>
    ///     文件读写辅助类
    /// </summary>
    public class FileHelper
    {
        private const double KbCount = 1024;
        private const double MbCount = KbCount * 1024;
        private const double GbCount = MbCount * 1024;
        private const double TbCount = GbCount * 1024;

        /// <summary>
        ///     生成树形文件Html
        /// </summary>
        /// <param name="builder">用于存放拼接的Html,由于是递归拼接,调用方法时,传入空的StringBuilder即可</param>
        /// <param name="path">要显示的服务器端文件夹路径(物理路径)</param>
        /// <param name="replacePath">要替换掉的路径部分</param>
        /// <returns></returns>
        public static string GetGuideTree(StringBuilder builder, string path, string replacePath)
        {
            var currentDir = new DirectoryInfo(path);
            var subDirs = currentDir.GetDirectories();
            if (subDirs.Length > 0)
            {
                builder.AppendFormat("<li><span class='folder' path='{0}'>{1}</span>" + Environment.NewLine,
                    currentDir.FullName.Replace(replacePath, ""), currentDir.Name);
                builder.Append("    <ul>" + Environment.NewLine);
                foreach (var dir in subDirs) GetGuideTree(builder, dir.FullName, replacePath);

                #region 文件夹下文件

                var files = currentDir.GetFiles();
                if (files.Length > 0)
                    foreach (var file in files)
                    {
                        var previewUrl = file.FullName.IsImage()
                            ? GetFileWebUrl(
                                file.FullName.Replace(HttpContext.Current.Server.MapPath("~/"), ""))
                            : string.Empty;
                        builder.AppendFormat(
                            "<li><span class='file' name='{0}' img='{1}' path='{2}'>{0}</span>" + Environment.NewLine,
                            file.Name,
                            previewUrl, file.FullName.Replace(replacePath, ""));
                    }

                builder.Append("    </ul>" + Environment.NewLine);

                #endregion

                builder.Append("</li>" + Environment.NewLine);
            }
            else
            {
                builder.AppendFormat(
                    "<li  class='closed'><span class='folder' path='{0}'>{1}</span>" + Environment.NewLine,
                    currentDir.FullName.Replace(replacePath, ""), currentDir.Name);

                #region 文件夹下文件

                var files = currentDir.GetFiles();
                if (files.Length > 0)
                {
                    builder.Append("    <ul>" + Environment.NewLine);
                    foreach (var file in files)
                    {
                        var previewUrl = file.FullName.IsImage()
                            ? GetFileWebUrl(
                                file.FullName.Replace(HttpContext.Current.Server.MapPath("~/"), ""))
                            : string.Empty;
                        builder.AppendFormat(
                            "<li><span class='file' name='{0}' img='{1}' path='{2}'>{0}</span>" + Environment.NewLine,
                            file.Name,
                            previewUrl, file.FullName.Replace(replacePath, ""));
                    }

                    builder.Append("    </ul>" + Environment.NewLine);
                }

                #endregion
            }

            return builder.ToString();
        }

        public static string GetFileWebUrl(string filePath)
        {
            if (filePath.IsEmpty()) return string.Empty;
            filePath = filePath.Replace("\\", "/");
            if (filePath.StartsWith("/")) filePath = filePath.TrimStart('/');
            return VirtualPathUtility.AppendTrailingSlash(HttpContext.Current.Request.ApplicationPath) + filePath;
        }

        /// <summary>
        ///     读取文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static string ReadFile(string filePath)
        {
            if (File.Exists(filePath))
            {
                var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                using (var sr = new StreamReader(fs, Encoding.UTF8))
                {
                    return sr.ReadToEnd();
                }
            }

            return string.Empty;
        }

        /// <summary>
        ///     取得文件编码
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static Encoding GetFileEncoding(string path)
        {
            var fileStream = File.Open(path, FileMode.Open, FileAccess.ReadWrite);
            var buffer = new byte[fileStream.Length];
            fileStream.Read(buffer, 0, buffer.Length);
            fileStream.Close();
            fileStream.Dispose();
            var fileEncoding = GetEncode(buffer);
            return fileEncoding;
        }

        /// <summary>
        ///     自适应编码读取文本
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static string GetTxt(string path)
        {
            var fileStream = File.Open(path, FileMode.Open, FileAccess.ReadWrite);
            var buffer = new byte[fileStream.Length];
            fileStream.Read(buffer, 0, buffer.Length);
            fileStream.Close();
            fileStream.Dispose();
            return GetTxt(buffer, GetEncode(buffer));
        }

        /// <summary>
        ///     按指定编码方式读取文本
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string GetTxt(byte[] buffer, Encoding encoding)
        {
            if (Equals(encoding, Encoding.UTF8))
                return encoding.GetString(buffer, 3, buffer.Length - 3);
            if (Equals(encoding, Encoding.BigEndianUnicode) || Equals(encoding, Encoding.Unicode))
                return encoding.GetString(buffer, 2, buffer.Length - 2);
            return encoding.GetString(buffer);
        }

        /// <summary>
        ///     取得文件编码方式
        /// </summary>
        /// <param name="buffer"></param>
        /// <returns></returns>
        public static Encoding GetEncode(byte[] buffer)
        {
            if (buffer.Length <= 0 || buffer[0] < 239)
                return Encoding.Default;
            if (buffer[0] == 239 && buffer[1] == 187 && buffer[2] == 191)
                return Encoding.UTF8;
            if (buffer[0] == 254 && buffer[1] == byte.MaxValue)
                return Encoding.BigEndianUnicode;
            if (buffer[0] == byte.MaxValue && buffer[1] == 254)
                return Encoding.Unicode;
            return Encoding.Default;
        }

        /// <summary>
        ///     写入文本
        /// </summary>
        /// <param name="filepath">写入文件</param>
        /// <param name="body">写入内容</param>
        /// <param name="encoding">编码方式</param>
        public static void WriteTxt(string filepath, string body, Encoding encoding)
        {
            if (File.Exists(filepath))
                File.Delete(filepath);
            var bytes = encoding.GetBytes(body);
            var fileStream = File.Open(filepath, FileMode.CreateNew, FileAccess.Write);
            if (Equals(encoding, Encoding.UTF8))
            {
                fileStream.WriteByte(239);
                fileStream.WriteByte(187);
                fileStream.WriteByte(191);
            }
            else if (Equals(encoding, Encoding.BigEndianUnicode))
            {
                fileStream.WriteByte(254);
                fileStream.WriteByte(byte.MaxValue);
            }
            else if (Equals(encoding, Encoding.Unicode))
            {
                fileStream.WriteByte(byte.MaxValue);
                fileStream.WriteByte(254);
            }

            fileStream.Write(bytes, 0, bytes.Length);
            fileStream.Flush();
            fileStream.Close();
            fileStream.Dispose();
        }

        /// <summary>
        ///     逐行读取文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public static List<string> ReadFileForLines(string filePath)
        {
            var lines = new List<string>();
            using (var sr = new StreamReader(filePath, Encoding.UTF8))
            {
                string input;
                while ((input = sr.ReadLine()) != null) lines.Add(input);
            }

            return lines;
        }

        /// <summary>
        ///     写入文件
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="content"></param>
        public static void WriteFile(string filePath, string content)
        {
            try
            {
                if (File.Exists(filePath)) File.Delete(filePath);
                using (var stream = new FileStream(filePath, FileMode.OpenOrCreate))
                {
                    var encode = Encoding.UTF8;
                    //获得字节数组
                    var data = encode.GetBytes(content);
                    //开始写入
                    stream.Write(data, 0, data.Length);
                    //清空缓冲区、关闭流
                    stream.Flush();
                    stream.Close();
                }
            }
            catch (Exception ex)
            {
            }
        }

        public static void GetFiles(string dir, List<string> list)
        {
            //添加文件
            list.AddRange(Directory.GetFiles(dir));

            //如果是目录,则递归
            var directories = new DirectoryInfo(dir).GetDirectories();
            foreach (var item in directories) GetFiles(item.FullName, list);
        }

        /// <summary>
        ///     复制文件(如果目标文件已存在将覆盖)。
        /// </summary>
        /// <param name="sourceFile">源文件。</param>
        /// <param name="destFile">目标文件。</param>
        public static bool CopyFile(string sourceFile, string destFile)
        {
            var copyResult = false;
            try
            {
                var directory = Path.GetDirectoryName(destFile);
                if (!Directory.Exists(directory)) Directory.CreateDirectory(directory);
                File.Copy(sourceFile, destFile, true);
            }
            catch (Exception)
            {
                copyResult = false;
            }

            return copyResult;
        }

        /// <summary>
        ///     获取指定文件夹下所有子文件夹路径。
        /// </summary>
        /// <param name="sourceDirectory">源文件夹。</param>
        /// <returns></returns>
        public static List<string> GetAllDirectory(string sourceDirectory)
        {
            var directorys = new List<string>();
            if (Directory.Exists(sourceDirectory))
            {
                var folders = Directory.GetDirectories(sourceDirectory);
                if (folders.Length > 0)
                    foreach (var folder in folders)
                    {
                        directorys.Add(folder);
                        directorys.AddRange(GetAllDirectory(folder));
                    }
            }

            return directorys;
        }

        /// <summary>
        ///     将指定文件夹(包括文件夹所有子目录和文件)拷贝到目标文件夹。
        /// </summary>
        /// <param name="sourceDirectory">需要拷贝的文件夹。</param>
        /// <param name="destDirectory">目标文件夹。</param>
        public static void CopyDirectory(string sourceDirectory, string destDirectory)
        {
            if (sourceDirectory != destDirectory)
                // 如果源文件夹存在。
                if (Directory.Exists(sourceDirectory))
                {
                    // 如果目标文件夹不存在
                    if (!Directory.Exists(destDirectory)) Directory.CreateDirectory(destDirectory);

                    // 拷贝根目录文件
                    var files = Directory.GetFiles(sourceDirectory);
                    foreach (var f in files)
                        CopyFile(f, Path.Combine(destDirectory, f.Substring(sourceDirectory.Length + 1)));

                    // 子目录拷贝以及文件拷贝
                    var directorys = GetAllDirectory(sourceDirectory);
                    directorys.ForEach(p =>
                    {
                        var path = Path.Combine(destDirectory + "\\",
                            p.Substring(sourceDirectory.Length + 1));
                        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                        var folderFiles = Directory.GetFiles(p);
                        foreach (var f in folderFiles) CopyFile(f, Path.Combine(path, f.Substring(p.Length + 1)));
                    });
                }
        }

        /// <summary>
        ///     删除文件夹(及文件夹下所有子文件夹和文件)
        /// </summary>
        /// <param name="directoryPath"></param>
        public static void DeleteFolder(string directoryPath)
        {
            try
            {
                foreach (var d in Directory.GetFileSystemEntries(directoryPath))
                    if (File.Exists(d))
                    {
                        var fi = new FileInfo(d);
                        if (fi.Attributes.ToString().IndexOf("ReadOnly", StringComparison.Ordinal) != -1)
                            fi.Attributes = FileAttributes.Normal;
                        File.Delete(d); //删除文件   
                    }
                    else
                    {
                        DeleteFolder(d); //删除文件夹
                    }

                Directory.Delete(directoryPath); //删除空文件夹
            }
            catch (Exception ex)
            {
            }
        }

        public static string GetSafeFileName(string name)
        {
            if (string.IsNullOrEmpty(name)) return string.Empty;
            name =
                new[]
                {
                    "//", ":", "*", "?", "<", ",", ">", "|", "'", "\"", "《", "》", ",", "。", "、", ":", "“", "”", "·",
                    "—",
                    "."
                }.Aggregate(name, (current, badChar) => current.Replace(badChar, ""));
            name = name.Length > 255 ? name.Substring(0, 250) : name;
            return name.Replace(" ", "_").Trim();
        }

        /// <summary>
        ///     得到文件的大小
        /// </summary>
        /// <param name="filepath">文件路径 </param>
        /// <param name="round">小数位 </param>
        /// <returns>string</returns>
        public static string GetFileSizeString(string filepath, int round)
        {
            if (File.Exists(filepath))
            {
                var file = new FileInfo(filepath);
                double size = file.Length;
                if (KbCount > size) return Math.Round(size, round) + "B";
                if (MbCount > size) return Math.Round(size / KbCount, round) + "KB";
                if (GbCount > size) return Math.Round(size / MbCount, round) + "MB";
                if (TbCount > size) return Math.Round(size / GbCount, round) + "GB";
                return Math.Round(size / TbCount, round) + "TB";
            }

            return string.Empty;
        }

        public static List<string> IterationAllFile(string path, List<string> eliminateFile,
            List<string> eliminateDirect)
        {
            var di = new DirectoryInfo(path);

            var paths = new List<string>();

            //取得当前目录中所有文件 
            var fiArray = di.GetFiles();

            //循环每一个文件 
            for (var i = 0; i < fiArray.Length; i++)
            {
                if (eliminateFile != null && eliminateFile.Contains(fiArray[i].ToString())) continue;
                paths.Add(path + "\\" + fiArray[i]);
            }

            //取得当前目录中所有子目录 
            var diArray = di.GetDirectories();

            //循环每一个目录 
            for (var j = 0; j < diArray.Length; j++)
            {
                if (eliminateDirect != null && eliminateDirect.Contains(diArray[j].Name)) continue;
                paths.AddRange(IterationAllFile(diArray[j].FullName, eliminateFile, eliminateDirect));
            }

            return paths;
        }
    }
}
        

如果觉得文章对您有帮助,您可以对我进行打赏 ¥1.68 元(金额随机^_^,每次刷新金额不同)。

请使用支付宝扫码支付

留言评论

*称  呼:
*联系方式: 方便与您取得联系,推荐使用邮箱。
*内  容:

已有评论

暂无数据

上一篇:Java 字符串操作辅助类

下一篇:MS SQL Server 查询数据表记录数及占用空间