[No000083]文件与文件夹操作
#region Folder option 文件夹操作 /// <summary> /// 指定目录是否存在 /// </summary> /// <param name="dirPath">文件夹路径</param> /// <returns></returns> public static bool DirExist(string dirPath) { try { if (Directory.Exists(dirPath)) { return true; } else { return false; } } catch (Exception ex) { Console.WriteLine("DirExit error" + ex.Message); return false; } } /// <summary> /// 创建目录 /// </summary> /// <param name="dirPath"></param> public static void MakeDir(string dirPath) { try { if (!DirExist(dirPath)) { Directory.CreateDirectory(dirPath); } } catch (Exception ex) { Console.WriteLine("MakeDir error" + ex.Message); //throw; } } #endregion Folder option 文件夹操作 #region File option 文件操作 /// <summary> /// 指定文件是否存在 /// </summary> /// <param name="filePath"></param> /// <returns></returns> public static bool FileExist(string filePath) { try { if (File.Exists(filePath)) { return true; } else { return false; } } catch (Exception ex) { Console.WriteLine("FileExist error" + ex.Message); return false; } } /// <summary> /// 读文件 /// </summary> /// <param name="filePath">文件路径</param> /// <returns></returns> public static string ReadFile(string filePath) { try { string content = ""; if (FileExist(filePath)) { StreamReader sr = new StreamReader(filePath, Encoding.UTF8); content = sr.ReadToEnd(); //读取全部内容 sr.Close(); } return content; } catch (Exception ex) { Console.WriteLine("ReadFile error" + ex.Message); return ""; } } /// <summary> /// 写文件 /// </summary> /// <param name="filePath">文件路径</param> /// <param name="content">写入的内容</param> public static void WriteFile(string filePath, string content) { try { string fileDirPath = Path.GetDirectoryName(filePath); if (!DirExist(fileDirPath)) { MakeDir(fileDirPath); } FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite); //创建写入文件 StreamWriter sw = new StreamWriter(fileStream, Encoding.UTF8); sw.WriteLine(content); //开始写入值 fileStream.Flush(); //确保全部写入 sw.Close(); fileStream.Close(); } catch (Exception ex) { Console.WriteLine("WriteFile error" + ex); } } #endregion File option 文件操作
摘抄自网络,便于检索查找。