FileDialogHelper.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217
  1. using System;
  2. using System.ComponentModel;
  3. using System.IO;
  4. using System.Runtime.InteropServices;
  5. using UnityEngine;
  6. public class FileDialogHelper
  7. {
  8. public class FileOpMsg
  9. {
  10. public bool success;
  11. public string msg;
  12. }
  13. public const string IMAGEFILTER = "图片文件(*.jpg;*.png)\0*.jpg;*.png";
  14. public const string ALLFILTER = "所有文件(*.*)\0*.*";
  15. public bool CopySelectFile(string sourcePath, string targetPath)
  16. {
  17. try
  18. {
  19. File.Copy(sourcePath, targetPath + $"/{Path.GetFileName(sourcePath)}", true);
  20. return true;
  21. }
  22. catch (Exception)
  23. {
  24. Debug.LogError($"sourcePath = {sourcePath}");
  25. Debug.LogError($"targetPath = {Path.GetFileName(sourcePath)}");
  26. Debug.LogError("拷贝失败");
  27. return false;
  28. }
  29. }
  30. public string SelectFile(Action<FileOpMsg> callback, string filter = ALLFILTER)
  31. {
  32. Debug.Log("open 00");
  33. FileOpMsg fileOpMsg = new FileOpMsg();
  34. try
  35. {
  36. OpenFileName openFileName = new OpenFileName();
  37. openFileName.structSize = Marshal.SizeOf(openFileName);
  38. //openFileName.hwndOwner = WindowsTools.ProcessHandle;
  39. openFileName.filter = filter;
  40. openFileName.file = new string(new char[256]);
  41. openFileName.maxFile = openFileName.file.Length;
  42. openFileName.fileTitle = new string(new char[64]);
  43. openFileName.maxFileTitle = openFileName.fileTitle.Length;
  44. openFileName.title = "选择文件";
  45. openFileName.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008;
  46. if (GetSaveFileName(openFileName))
  47. {
  48. string filepath = openFileName.file; //选择的文件路径;
  49. if (File.Exists(filepath))
  50. {
  51. fileOpMsg.success = true;
  52. fileOpMsg.msg = filepath;
  53. callback?.Invoke(fileOpMsg);
  54. return fileOpMsg.msg;
  55. }
  56. }
  57. }
  58. catch (Exception e)
  59. {
  60. fileOpMsg.success = false;
  61. fileOpMsg.msg = e.ToString();
  62. callback?.Invoke(fileOpMsg);
  63. Debug.LogError(fileOpMsg.msg);
  64. return fileOpMsg.msg;
  65. }
  66. fileOpMsg.success = true;
  67. fileOpMsg.msg = string.Empty;
  68. callback?.Invoke(fileOpMsg);
  69. return fileOpMsg.msg;
  70. }
  71. [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
  72. private static extern bool GetSaveFileName([In, Out] OpenFileName ofn);
  73. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
  74. public class OpenFileName
  75. {
  76. public int structSize = 0;
  77. public IntPtr dlgOwner = IntPtr.Zero;
  78. public IntPtr instance = IntPtr.Zero;
  79. public String filter = null;
  80. public String customFilter = null;
  81. public int maxCustFilter = 0;
  82. public int filterIndex = 0;
  83. public String file = null;
  84. public int maxFile = 0;
  85. public String fileTitle = null;
  86. public int maxFileTitle = 0;
  87. public String initialDir = null;
  88. public String title = null;
  89. public int flags = 0;
  90. public short fileOffset = 0;
  91. public short fileExtension = 0;
  92. public String defExt = null;
  93. public IntPtr custData = IntPtr.Zero;
  94. public IntPtr hook = IntPtr.Zero;
  95. public String templateName = null;
  96. public IntPtr reservedPtr = IntPtr.Zero;
  97. public int reservedInt = 0;
  98. public int flagsEx = 0;
  99. }
  100. #region 隐藏
  101. /// <summary> 用于显示Windows平台的标准文件对话框 </summary>
  102. /// <param name="ofn"></param>
  103. /// <returns>返回用户所选文件的路径信息</returns>
  104. // 引入外部库,SetLastError = true将上一个错误代码设置为非零值,CharSet = CharSet.Auto字符集由运行时环境自动选择
  105. ///[In, Out]是修饰符,用于指定参数是既输入又输出的(类似于引用传参)
  106. [DllImport("Comdlg32.dll", SetLastError = true, CharSet = CharSet.Auto)]
  107. private static extern bool GetOpenFileName([In, Out] FileDialogWin ofn);
  108. [DllImport("kernel32.dll")]
  109. private static extern uint GetLastError();
  110. /// <summary>
  111. /// 打开文件对话框
  112. /// </summary>
  113. /// <param name="title">对话框标题</param>
  114. /// <param name="defaultPath">对话框默认路径</param>
  115. /// <param name="extension">文件默认格式</param>
  116. /// <returns></returns>
  117. public string OpenWindowsFileDialog(string title, string defaultPath, string extension)
  118. {
  119. #if UNITY_EDITOR
  120. return UnityEditor.EditorUtility.OpenFilePanel(title, defaultPath, extension);
  121. #else
  122. // 在运行时用原生对话框
  123. FileDialogWin ofn = new FileDialogWin();
  124. ofn.structSize = Marshal.SizeOf(ofn);
  125. ofn.filter = extension;
  126. ofn.file = new string(new char[256]);
  127. ofn.maxFile = ofn.file.Length;
  128. ofn.title = title;
  129. ofn.initialDir = defaultPath;
  130. ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008;
  131. bool result = GetOpenFileName(ofn);
  132. Debug.LogError($"ofn = {ofn}");
  133. Debug.LogError($"result: {result}");
  134. if (!result)
  135. {
  136. uint errorCode = GetLastError();
  137. Debug.LogError($"errorCode = {errorCode}");
  138. if (errorCode == 0)
  139. {
  140. // 用户取消了对话框,这是正常行为
  141. Debug.Log("用户取消了文件选择");
  142. return null;
  143. }
  144. else
  145. {
  146. string errorMessage = new Win32Exception((int)errorCode).Message;
  147. Debug.LogError($"打开文件对话框失败,错误代码: {errorCode}, 错误信息: {errorMessage}");
  148. // 常见的错误代码
  149. switch (errorCode)
  150. {
  151. case 0x00000002: // ERROR_FILE_NOT_FOUND
  152. Debug.LogError("文件未找到,请检查默认路径是否存在");
  153. break;
  154. case 0x00000005: // ERROR_ACCESS_DENIED
  155. Debug.LogError("访问被拒绝,可能没有足够的权限");
  156. break;
  157. case 0x00000057: // ERROR_INVALID_PARAMETER
  158. Debug.LogError("参数无效,请检查结构体字段设置");
  159. break;
  160. }
  161. }
  162. return null;
  163. }
  164. return ofn.file;
  165. #endif
  166. }
  167. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
  168. public class FileDialogWin
  169. {
  170. public int structSize = 0;
  171. public IntPtr dlgOwner = IntPtr.Zero;
  172. public IntPtr instance = IntPtr.Zero;
  173. public string filter = null;
  174. public string customFilter = null;
  175. public int maxCustFilter = 0;
  176. public int filterIndex = 0;
  177. public string file = null;
  178. public int maxFile = 0;
  179. public string initialDir = null;
  180. public string title = null;
  181. public int flags = 0;
  182. public short fileOffset = 0;
  183. public short fileExtension = 0;
  184. public string defExt = null;
  185. public IntPtr custData = IntPtr.Zero;
  186. public IntPtr hook = IntPtr.Zero;
  187. public string templateName = null;
  188. public IntPtr reservedPtr = IntPtr.Zero;
  189. public int reservedInt = 0;
  190. public int flagsEx = 0;
  191. }
  192. #endregion
  193. }