FileHelper

本文详细介绍了一套C#文件操作实用工具类,包括文件创建、读写、删除及路径处理等功能,支持多种文件类型如文本、二进制、Excel等,并提供了文件对话框选择功能。
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;
        }
    }

}

 

<think>我们在之前的对话中讨论了用户的问题:用户想要查找FileHelper.Load方法的相关用法或解决问题。由于这是一个编程相关的问题,可能涉及特定的库或框架,我们需要提供关于该方法的基本用法和常见问题的解决方案。首先,我们假设FileHelper是一个文件操作辅助类,而Load是它的一个静态方法,用于从文件中加载数据。但是,由于不同的库可能有不同的实现,这里我们以一般性的角度来解答。常见的FileHelper.Load方法可能用于加载文件内容,例如文本、二进制数据或反序列化对象。下面我们将分步骤介绍其典型用法,并讨论可能遇到的问题。步骤1:引入命名空间首先,确保已经引用了包含FileHelper类的命名空间。例如:```csharpusingMyCompany.Utilities;//假设的命名空间```步骤2:使用Load方法加载文件Load方法可能有多种重载,常见的包括指定文件路径和编码方式。示例1:加载文本文件```csharpstringcontent=FileHelper.Load("example.txt");```示例2:加载文件并指定编码```csharpstringcontent=FileHelper.Load("example.txt",Encoding.UTF8);```步骤3:处理加载的数据根据文件内容,你可能需要进一步处理字符串,比如反序列化JSON或XML。常见问题及解决方案:问题1:文件不存在当文件不存在时,Load方法可能会抛出FileNotFoundException。为了避免程序崩溃,可以先检查文件是否存在。解决方案:```csharpif(File.Exists("example.txt")){stringcontent=FileHelper.Load("example.txt");}else{//处理文件不存在的情况}```或者,在Load方法内部可能已经处理了异常,但通常我们建议在调用前检查。问题2:权限不足如果应用程序没有访问文件的权限,会抛出UnauthorizedAccessException。确保应用程序具有读取目标文件的权限。问题3:路径格式错误如果文件路径包含无效字符或格式不正确,会抛出ArgumentException或PathTooLongException。使用Path类的方法来验证路径。示例3:处理路径```csharpstringpath="example.txt";if(Path.GetInvalidPathChars().Any(path.Contains)){//路径包含无效字符}```问题4:文件正在被其他进程占用如果文件被其他进程独占打开,会抛出IOException。可以尝试等待并重试,或者使用文件流共享模式(如果FileHelper允许设置的话)。由于用户没有指定具体的语言或库,以上示例以C#为例,但原理相通。如果用户使用的是特定的库(如FileHelpers库,这是一个处理固定长度文件或分隔文件的库),那么Load(或Read)方法的使用可能有所不同。例如,在FileHelpers库中,通常使用引擎来读取文件:```csharpvarengine=newFileHelperEngine<Customer>();Customer[]customers=engine.ReadFile("customers.txt");```因此,如果用户的问题是关于FileHelpers库(一个流行的.NET库)的,我们需要提供针对该库的用法。但用户的问题中写的是“FileHelper.Load”,这可能是一个自定义的类。为了更准确地帮助用户,我们需要更多的上下文,比如:-使用什么编程语言?-是哪个库或框架中的FileHelper类?但是,由于用户没有提供,我们只能给出通用答案。最后,生成相关问题以帮助用户深入探索:</think> 以下是对 `FileHelper.Load` 方法的用法解析和常见问题解决方案的总结(基于一般性.NET类库设计模式): ### FileHelper.Load 方法常见用法 --- #### 1. **基本语法结构** ```csharp // 从文件加载数据 var data = FileHelper.Load(string filePath); // 指定编码格式加载 var data = FileHelper.Load(string filePath, Encoding encoding); // 带异常处理的典型用法 try { var content = FileHelper.Load("data.txt"); Console.WriteLine(content); } catch (FileNotFoundException ex) { Console.WriteLine($"文件不存在: {ex.Message}"); } ``` #### 2. **核心功能** - ✅ **文件读取**:直接返回文件内容(通常为 `string` 或 `byte[]`) - ✅ **自动资源管理**:内部实现 `using` 语句确保文件流关闭 - ✅ **异常封装**:统一处理常见文件错误(路径无效、权限不足等) #### 3. **典型场景示例** ```csharp // 加载配置文件 var config = FileHelper.Load("appsettings.json"); // 读取二进制文件 byte[] imageData = FileHelper.Load("photo.png") as byte[]; // 配合反序列化 var users = JsonSerializer.Deserialize<List<User>>( FileHelper.Load("users.json") ); ``` --- ### 常见问题解决指南 #### ❗ **问题1:文件路径错误** **症状**:抛出 `FileNotFoundException` **解决方案**: ```csharp // 使用绝对路径替代相对路径 string fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "data.dat"); FileHelper.Load(fullPath); // 路径验证 if (!File.Exists(filePath)) throw new CustomException("无效路径"); ``` #### ❗ **问题2:编码格式冲突** **症状**:读取内容出现乱码 **修复方案**: ```csharp // 显式指定编码 FileHelper.Load("data.txt", Encoding.UTF8); // 自动检测编码(需扩展方法) public static string LoadWithDetectEncoding(string path) { using var reader = new StreamReader(path, true); // 自动检测 return reader.ReadToEnd(); } ``` #### ❗ **问题3:大型文件性能问题** **优化策略**: ```csharp // 分块读取(伪代码) public static IEnumerable<string> LoadChunked(string path, int bufferSize=4096) { using var reader = new StreamReader(path); while (!reader.EndOfStream) { yield return reader.ReadBlock(bufferSize); } } ``` --- ### 最佳实践建议 1. **防御性编程** 始终添加异常处理层,特别是在移动端/Web环境: ```csharp try { return FileHelper.Load(path); } catch (IOException ex) when (ex.HResult == 0x80070020) { // 文件被占用特殊处理 } ``` 2. **扩展方法封装** ```csharp public static class FileHelperExtensions { public static T LoadJson<T>(this FileHelper helper, string path) { return JsonConvert.DeserializeObject<T>(FileHelper.Load(path)); } } ``` 3. **跨平台兼容** 使用 `Path.DirectorySeparatorChar` 替代硬编码路径分隔符 --- ### 底层机制要点 | 核心组件 | 作用 | 相关异常 | |----------------|----------------------------------|--------------------------| | FileStream | 底层文件流操作 | IOException, UnauthorizedAccessException | | StreamReader | 字符流解码(文本文件) | DecoderFallbackException | | MemoryStream | 二进制数据缓存(非文本文件) | OutOfMemoryException | > 📌 **注意**:具体实现可能因库版本而异,请参考官方文档 [FileHelpers Library Documentation](https://www.filehelpers.net/docs/)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值