FileHelper

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Intesim.Common
{
    public class FileHelper
    {

        /// <summary>
        /// 默认多字节字符串编码
        /// </summary>
        public static readonly Encoding DEFAULT_ANSI_ENCODING = Encoding.GetEncoding(936);

        /// <summary>
        /// 默认文件编码
        /// </summary>
        public static readonly Encoding DEFAULT_FILE_ENCODING = DEFAULT_ANSI_ENCODING;

        /// <summary>
        /// Windows 路径分隔符
        /// </summary>
        public const string WINDOWS_PATH_SPLITTER = @"\";

        #region 文件扩展名

        /// <summary>
        /// 可执行文件扩展名
        /// </summary>
        public const string EXE_EXT = ".exe";

        /// <summary>
        /// 逗号分隔文件扩展名
        /// </summary>
        public const string CSV_EXT = ".csv";

        /// <summary>
        /// Python 文件扩展名
        /// </summary>
        public const string PYTHON_FILENAME_EXT = ".py";

        #endregion

        #region 文件名过滤器

        /// <summary>
        /// 所有文件过滤器
        /// </summary>
        public const string ALL_FILE_FILTER = "所有文件 (*.*)|*.*";

        /// <summary>
        /// 可执行文件过滤器
        /// </summary>
        public const string EXE_FILE_FILTER = "可执行文件 (*" + EXE_EXT + ")|*" + EXE_EXT;

        /// <summary>
        /// 逗号分隔符文件过滤器
        /// </summary>
        public const string CSV_FILE_FILTER = "逗号分隔符文件 (*" + CSV_EXT + ")|*" + CSV_EXT;

        /// <summary>
        /// 所有图片过滤器
        /// </summary>
        public const string ALL_PIC_FILTER = "所有图片|*.jpg;*.png;*.bmp";

        /// <summary>
        /// Excel文件过滤器
        /// </summary>
        public const string EXCEL_FILE_FILTER = "Excel 工作簿(*.xlsx)|*.xlsx|Excel 97-2003 工作簿(*.xls)|*.xls";

        #endregion

        public static void CreateFile(string filePath, string text, Encoding encoding)
        {
            try
            {
                if (IsExistFile(filePath))
                {
                    DeleteFile(filePath);
                }
                if (!IsExistFile(filePath))
                {
                    string directoryPath = GetDirectoryFromFilePath(filePath);
                    CreateDirectory(directoryPath);

                    //Create File
                    FileInfo file = new FileInfo(filePath);
                    using (FileStream stream = file.Create())
                    {
                        using (StreamWriter writer = new StreamWriter(stream, encoding))
                        {
                            writer.Write(text);
                            writer.Flush();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public static bool IsExistDirectory(string directoryPath)
        {
            return Directory.Exists(directoryPath);
        }
        public static void CreateDirectory(string directoryPath)
        {
            if (!IsExistDirectory(directoryPath))
            {
                Directory.CreateDirectory(directoryPath);
            }
        }
        public static void DeleteFile(string filePath)
        {
            if (IsExistFile(filePath))
            {
                File.Delete(filePath);
            }
        }
        public static string GetDirectoryFromFilePath(string filePath)
        {
            FileInfo file = new FileInfo(filePath);
            DirectoryInfo directory = file.Directory;
            return directory.FullName;
        }
        public static bool IsExistFile(string filePath)
        {
            return File.Exists(filePath);
        }


        /// <summary>
        /// 确保目录名以路径分隔符结尾
        /// </summary>
        /// <param name="dirpath">目录名</param>
        /// <returns>以路径分隔符结尾的目录名</returns>
        public static string MakeSureEndWithPathSplitter(string dirpath)
        {
            if (string.IsNullOrEmpty(dirpath))
            {
                return string.Empty;
            }
            else
            {
                if (!dirpath.EndsWith(WINDOWS_PATH_SPLITTER))
                {
                    return dirpath + WINDOWS_PATH_SPLITTER;
                }
                else
                {
                    return dirpath.TrimEnd(WINDOWS_PATH_SPLITTER.ToCharArray()) + WINDOWS_PATH_SPLITTER;
                }
            }
        }

        /// <summary>
        /// 确保文件对应的文件夹存在
        /// </summary>
        /// <returns>是否成功</returns>
        public static bool MakeSureFileFolderExists(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                return false;
            }
            else
            {
                try
                {
                    return MakeSureFolderExists(new FileInfo(filePath).Directory.FullName);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("生成文件信息对象失败:" + ex.Message);
                    return false;
                }
            }
        }

        /// <summary>
        /// 确保文件夹存在
        /// </summary>
        /// <returns></returns>
        public static bool MakeSureFolderExists(string folderPath)
        {
            if (string.IsNullOrEmpty(folderPath))
            {
                return false;
            }
            if (Directory.Exists(folderPath))
            {
                return true;
            }
            else
            {
                try
                {
                    return Directory.CreateDirectory(folderPath) != null;
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("创建文件夹失败:" + ex.Message);
                    return false;
                }
            }
        }

        /// <summary>
        /// 选择打开文件路径(使用打开文件对话框)
        /// </summary>
        /// <param name="defaultExt">默认文件扩展名</param>
        /// <param name="filter">文件名筛选器字符串</param>
        /// <param name="initDirectory">初始目录</param>
        /// <param name="title">对话框标题</param>
        /// <param name="initFilename">初始文件名</param>
        /// <returns>对话框返回的文件名</returns>
        public static string SelectOpenFile(string defaultExt, string filter, string initDirectory, string title, string initFilename = null)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.AddExtension = true;
            ofd.AutoUpgradeEnabled = true;
            ofd.CheckPathExists = true;
            ofd.DefaultExt = defaultExt;
            ofd.Filter = filter;
            ofd.RestoreDirectory = true;
            if (!string.IsNullOrEmpty(initDirectory))
            {
                ofd.InitialDirectory = initDirectory;
            }
            ofd.Title = title;
            if (!string.IsNullOrEmpty(initFilename))
            {
                ofd.FileName = initFilename;
            }
            if (ofd.ShowDialog() != System.Windows.Forms.DialogResult.OK
                || string.IsNullOrEmpty(ofd.FileName)
                || !File.Exists(ofd.FileName)
                )
            {
                return null;
            }

            return ofd.FileName;
        }

        /// <summary>
        /// 选择打开文件路径(使用打开文件对话框)
        /// </summary>
        /// <param name="defaultExt">默认文件扩展名</param>
        /// <param name="filter">文件名筛选器字符串</param>
        /// <param name="initDirectory">初始目录</param>
        /// <param name="title">对话框标题</param>
        /// <param name="initFilename">初始文件名</param>
        /// <returns>对话框返回的文件名</returns>
        public static string[] MultiselectSelectOpenFile(string defaultExt, string filter, string initDirectory, string title, string initFilename = null)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.AddExtension = true;
            ofd.Multiselect = true;
            ofd.AutoUpgradeEnabled = true;
            ofd.CheckPathExists = true;
            ofd.DefaultExt = defaultExt;
            ofd.Filter = filter;
            ofd.RestoreDirectory = true;
            if (!string.IsNullOrEmpty(initDirectory))
            {
                ofd.InitialDirectory = initDirectory;
            }
            ofd.Title = title;
            if (!string.IsNullOrEmpty(initFilename))
            {
                ofd.FileName = initFilename;
            }
            if (ofd.ShowDialog() != System.Windows.Forms.DialogResult.OK
                || string.IsNullOrEmpty(ofd.FileName)
                || !File.Exists(ofd.FileName)
                )
            {
                return null;
            }

            return ofd.FileNames;
        }

        /// <summary>
        /// 选择保存文件路径(使用保存文件对话框)
        /// </summary>
        /// <param name="defaultExt">默认文件扩展名</param>
        /// <param name="filter">文件名筛选器字符串</param>
        /// <param name="initDirectory">初始目录</param>
        /// <param name="title">对话框标题</param>
        /// <param name="initFilename">初始文件名</param>
        /// <returns>对话框返回的文件名</returns>
        public static string SelectSaveFile(string defaultExt, string filter, string initDirectory, string title, string initFilename = null)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.AddExtension = true;
            sfd.AutoUpgradeEnabled = true;
            sfd.CheckPathExists = true;
            sfd.DefaultExt = defaultExt;
            sfd.Filter = filter;
            sfd.RestoreDirectory = true;
            if (!string.IsNullOrEmpty(initDirectory))
            {
                sfd.InitialDirectory = initDirectory;
            }
            sfd.Title = title;
            if (!string.IsNullOrEmpty(initFilename))
            {
                sfd.FileName = initFilename;
            }
            if (sfd.ShowDialog() != System.Windows.Forms.DialogResult.OK
                || string.IsNullOrEmpty(sfd.FileName))
            {
                return null;
            }

            return sfd.FileName;
        }

        /// <summary>
        /// 选择文件夹(使用浏览文件夹对话框)
        /// </summary>
        /// <param name="rootFolder">根文件夹</param>
        /// <param name="title">对话框标题</param>
        /// <param name="initPath">初始路径</param>
        /// <returns>对话框返回的文件夹路径</returns>
        public static string SelectFolder(Environment.SpecialFolder rootFolder, string title, IWin32Window ownWnd, string initPath = null)
        {
            FolderBrowserDialog fbd = new FolderBrowserDialog();
            fbd.RootFolder = rootFolder;
            fbd.Description = title;
            fbd.ShowNewFolderButton = true;
            if (!string.IsNullOrEmpty(initPath))
            {
                fbd.SelectedPath = initPath;
            }

            DialogResult dlgRslt = fbd.ShowDialog(ownWnd);  // 显示模态对话框,选择文件夹
            if (dlgRslt != DialogResult.OK
                || string.IsNullOrEmpty(fbd.SelectedPath)
                || !Directory.Exists(fbd.SelectedPath)
                )
            {
                return null;
            }

            return fbd.SelectedPath;
        }

        /// <summary>
        /// 读取文本文件内容
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns>文本文件内容,失败返回 null</returns>
        public static string ReadTextFile(string path)
        {
            if (!File.Exists(path))
            {
                return null;
            }

            try
            {
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    StreamReader sr = new StreamReader(fs, DEFAULT_FILE_ENCODING);
                    string strContent = sr.ReadToEnd();  // 读到文件结尾

                    sr.Close();
                    fs.Close();

                    return strContent;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("打开文件出错:消息={0},堆栈={1}", ex.Message, ex.StackTrace));
                return null;
            }
        }

        /// <summary>
        /// 读取二进制文件内容
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns>二进制文件内容,失败返回 null</returns>
        public static byte[] ReadBinaryFile(string path)
        {
            if (!File.Exists(path))
            {
                return null;
            }

            try
            {
                using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read))
                {
                    byte[] buf = new byte[fs.Length];
                    fs.Read(buf, 0, buf.Length);
                    fs.Close();
                    return buf;
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("打开文件出错:消息={0},堆栈={1}", ex.Message, ex.StackTrace));
                return null;
            }
        }

        /// <summary>
        /// 保存文件文件内容
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="content">需写入的内容</param>
        /// <returns>成功返回 true,失败返回 false</returns>
        public static bool SaveTextFile(string path, string content)
        {
            if (!MakeSureFileFolderExists(path)
                || string.IsNullOrEmpty(content)
                )
            {
                return false;
            }

            try
            {
                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    StreamWriter sw = new StreamWriter(fs, DEFAULT_FILE_ENCODING);
                    sw.Write(content);
                    sw.Close();
                }

                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("写入文件出错:消息={0},堆栈={1}", ex.Message, ex.StackTrace));
                return false;
            }
        }

        /// <summary>
        /// 保存二进制文件内容
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <param name="buf">需写入的缓冲区</param>
        /// <returns>成功返回 true,失败返回 false</returns>
        public static bool SaveBinaryFile(string path, byte[] buf)
        {
            if (!MakeSureFileFolderExists(path)
                || buf == null
                )
            {
                return false;
            }

            try
            {
                using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    fs.Write(buf, 0, buf.Length);
                    fs.Close();
                }

                return true;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(string.Format("写入文件出错:消息={0},堆栈={1}", ex.Message, ex.StackTrace));
                return false;
            }
        }

        /// <summary>
        /// 读取流并保存文件-循环读取
        /// </summary>
        /// <param name="path">保存路径</param>
        /// <param name="stream">流</param>
        /// <returns></returns>
        public static bool SaveCircleBinaryFile(string path, Stream stream)
        {

            if (!MakeSureFileFolderExists(path) || stream == null)
            {
                return false;
            }

            try
            {
                FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write);

                byte[] srcBuf = new byte[1024 * 1024];
                int initSize = 0;

                while ((initSize = stream.Read(srcBuf, 0, srcBuf.Length)) > 0)
                {
                    fs.Write(srcBuf, 0, initSize);
                    fs.Flush();
                }
                fs.Close();

                return true;
            }
            catch (Exception e)
            {
                Debug.WriteLine(string.Format("写入文件出错:消息={0},堆栈={1}", e.Message, e.StackTrace));
                return false;
            }
        }

        /// <summary>
        /// 读取大文件,每次读取1M,优化可考虑分割读取
        /// </summary>
        /// <returns></returns>
        public static string ReadBinaryFileToString(FileStream fs)
        {
            if (fs != null)
            {
                string returnStr = ""; //保存结果字符串
                try
                {
                    byte[] byteArray = new byte[1024 * 1024];//开辟1M内存空间

                    BinaryReader reader = new BinaryReader(fs);

                    while (reader.Read(byteArray, 0, byteArray.Length) > 0)
                    {
                        string content = DEFAULT_FILE_ENCODING.GetString(byteArray);
                        returnStr += content;
                    }

                    return returnStr;
                }
                catch (Exception e)
                {
                    Debug.WriteLine(string.Format("读取文件出错:消息={0},堆栈={1}", e.Message, e.StackTrace));
                }
            }
            return null;
        }
    }

}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值