FileManager.cs 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using UnityEngine;
  5. namespace FSFile {
  6. /*
  7. * 文件系统,用来读取和保存
  8. */
  9. public class FileManager : Singleton<FileManager>
  10. {
  11. /*
  12. * 根据文件名来读取Resource中的文本数据
  13. */
  14. public string ReadResourceText(string file) {
  15. try {
  16. string value = ((TextAsset)Resources.Load(file)).text;
  17. return value;
  18. } catch (System.NullReferenceException e) {
  19. Debug.Log(e.Message);
  20. return null;
  21. }
  22. }
  23. /*
  24. * 读取指定路径的文本数据
  25. */
  26. public string ReadTextFile(string path) {
  27. // 首先判断文件是否存在
  28. if (IsFileExists(path)) {
  29. return File.ReadAllText(path);
  30. }
  31. return null;
  32. }
  33. /*
  34. * 传入路径和要保存的字符
  35. */
  36. public void SaveTextToFile(string path, string value) {
  37. // 找到当前路径
  38. FileInfo file = new FileInfo(path);
  39. // 判断有没有文件,有则打开,没有则创建后打开
  40. StreamWriter stream = file.CreateText();
  41. // 将字符串存进文件中
  42. stream.WriteLine(value);
  43. // 释放资源
  44. stream.Close();
  45. stream.Dispose();
  46. }
  47. /*
  48. * 传入要保存的文件夹,文件和文本
  49. */
  50. public void SaveText(string dir, string file, string value) {
  51. // 判断是否存在该文件
  52. if (!IsDirectorExists(dir))
  53. Directory.CreateDirectory(dir);
  54. SaveTextToFile(dir + "/" + file, value);
  55. }
  56. /*
  57. * 删除指定路径的文件
  58. */
  59. public void RemoveFile(string path) {
  60. // 查看文件是否存在
  61. if (IsFileExists(path)) {
  62. // 将其删除
  63. FileInfo file = new FileInfo(path);
  64. file.Delete();
  65. }
  66. }
  67. /*
  68. * 删除指定路径的文件夹
  69. */
  70. public void RemoveDirector(string path) {
  71. // 查看文件夹
  72. if (IsDirectorExists(path)) {
  73. // 将文件夹删除
  74. DirectoryInfo directory = new DirectoryInfo(path);
  75. directory.Delete();
  76. }
  77. }
  78. /*
  79. * 检查文件夹下的文件
  80. * 传入路径和要传入的文件类型
  81. */
  82. public ArrayList CheckFilesInDirector(string path, string type) {
  83. // 判断文件夹是否存在
  84. if (IsDirectorExists(path)) {
  85. DirectoryInfo info = new DirectoryInfo(path);
  86. FileInfo[] files = info.GetFiles("*." + type, SearchOption.TopDirectoryOnly);
  87. // 将文件名放入数组中保存返回
  88. ArrayList names = new ArrayList();
  89. // 遍历文件夹,输出内容
  90. foreach (FileInfo file in files)
  91. names.Add(file.Name.Substring(0, file.Name.Length - (1 + type.Length)));
  92. return names;
  93. }
  94. return null;
  95. }
  96. /*
  97. * 判断指定路径的文件是否存在
  98. */
  99. public bool IsFileExists(string path) {
  100. return File.Exists(path);
  101. }
  102. /*
  103. * 判断文件夹是否存在
  104. */
  105. public bool IsDirectorExists(string path) {
  106. return Directory.Exists(path);
  107. }
  108. }
  109. }