using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace FlieOperate { /// /// 关于文件的 操作类 /// public class FileBase { /// /// 资源管理器 文件类型 中文说明 和扩展名是 成对关系 数组长度要一致 /// public static string[] FileClass { get; set; } = new string[] { "航点文件" }; /// /// 扩展名 ps: "*.jpg;*.png" 这个格式算一组 /// public static string[] Pascal { get; set; } = new string[] { "*.fcgm;" }; /// /// 整合文件类型及扩展名 /// "航点文件|*.fcgm;*.txt|航点文件|*.fcgm;*.*";//资源管理器限制扩展名 例子 /// /// 文件类型及扩展名 private static string SetFileClass() { string str = ""; for (int i = 0; i < FileClass.Length; i++) { str += FileClass[i] + "|" + Pascal[i]; if (i + 1 != FileClass.Length)//最后一次 不加| { str += "|"; } } return str; } /// /// 读取文件 存到字符串 /// /// 文件路径 /// 文件内容 字符串 public static string ReadFlieToStr(string FliePath) { FileStream fs = new FileStream(FliePath, FileMode.Open); StreamReader fileStream = new StreamReader(fs); string str = ""; string line; while ((line = fileStream.ReadLine()) != null) { str += line; } return str; } /// /// 字符串 保存到指定文件 /// /// 指定文件和路径 /// 字符串 private static void SaveStrToFile(string filePath, string str) { str = str.TrimEnd((char[])"\n\r".ToCharArray());//去除最后的回车符 string stream = null; if (File.Exists(filePath)) { StreamReader reader = new StreamReader(filePath); stream = reader.ReadToEnd(); reader.Close(); } FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate); StreamWriter sw = new StreamWriter(fs); sw.Write(str); sw.Close(); fs.Close(); } public static void SaveExplorer(string str) { SaveFileDialog sfd = new SaveFileDialog(); sfd.Filter = SetFileClass();//设置文件类型 sfd.AddExtension = true;//设置自动在文件名中添加扩展名 if (sfd.ShowDialog() == DialogResult.OK) { SaveStrToFile(sfd.FileName, str); } } /// /// 资源管理器 获取文件路径 /// /// 资源管理器标题栏 /// out参数 判断是否获取到文件路径 /// 文件路径 public static string OpenExplorer(string titName, out bool isSelect) { Microsoft.Win32.OpenFileDialog ofdl = new Microsoft.Win32.OpenFileDialog();//打开资源管理器 ofdl.Filter = SetFileClass();//设置文件类型 ofdl.Title = titName; if (ofdl.ShowDialog() == true)//执行打开资源管理器 并判断有没有获取到文件名 { isSelect = true; } else { isSelect = false; } return ofdl.FileName; } } }