unity 打开系统文件

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using System;


public class Form_Window : MonoBehaviour, Form
{
    public const string filter_Image = "图片文件(*.jpg;*.png)\0*.jpg;*.png";
    public const string filter_All = "所有文件(*.*)\0*.*";
    public const string filter_Excel = "excel(*.xls;*.xlsx)\0*.xls;*.xlsx\0xlsx(*.xlsx)\0*.xlsx\0xls(*.xls)\0*.xls";

    private void Start()
    {
        string folderPath = UnityEngine.Application.streamingAssetsPath; 
        
        // SelectFile();
        // SelectFile(folderPath, filter_Excel);
        // SelectFile_Dll(folderPath, filter_Excel); 
        
        // SelectSaveFile(folderPath);

        // SelectFolder();
        // SelectFolder(folderPath);
        // SelectFolder_Dll(folderPath);
        // SelectFolder_Dialog(folderPath); 
    }


    public void SelectFile(string folderPath = null, string filter = null, System.Action<FileData> callBack = null)
    {
        switch (0)
        {
            case 0:
            case 1:
                SelectFile_Dialog(folderPath, filter, callBack);
                break;
            case 2:
                SelectFile_Dll(folderPath, filter, callBack);
                break;
        }
    }

    private void SelectFile_Dll(string folderPath = null, string filter = null, System.Action<FileData> callBack = null)
    {
        System.Windows.Forms.OpenFileDialog dialog = new System.Windows.Forms.OpenFileDialog();
        dialog.Filter = filter.Replace("\0","|"); //过滤文件类型 //(*.txt)|*.txt|All files (*.*)|*.*
        dialog.InitialDirectory = folderPath; //定义打开的默认文件夹位置,可以在显示对话框之前设置好各种属性

        if (dialog.ShowDialog() == DialogResult.OK)
        {
            FileData fileData = new FileData();
            fileData.FileDatas = dialog.FileName;
            fileData.ToString();

            callBack?.Invoke(fileData); //全路径
        }
    }

    private void SelectFile_Dialog(string folderPath = null, string filter = null,
        System.Action<FileData> callBack = null)
    {
        OpenFileDialog dialog = new OpenFileDialog();
        dialog = dialog.GetOpenFileDialog(folderPath, filter);

        if (WindowDll.GetOpenFileName(dialog))
        {
            FileData fileData = new FileData();
            fileData.FileDatas = dialog.file;
            fileData.ToString();

            callBack?.Invoke(fileData);
        }
    }


    public void SelectSaveFile(string folderPath = null, string filter = null, Action<string, bool> callBack = null)
    {
        OpenFileDialog dialog = new OpenFileDialog();
        dialog = dialog.GetOpenFileDialog(folderPath, filter, true);

        if (WindowDll.GetSaveFileName(dialog))
        {
            string filePath = dialog.file;
            callBack?.Invoke(filePath, System.IO.File.Exists(filePath));
        }
    }


    public void SelectFolder(string folderPath = null, System.Action<string> callBack = null)
    {
        switch (0)
        {
            case 0:
                SelectFolder_Ookii(folderPath, callBack);
                break;
            case 1:
                SelectFolder_Dialog(folderPath, callBack);
                break;
            case 2:
                SelectFolder_Dll(folderPath, callBack);
                break;
        }
    }
    
    private void SelectFolder_Ookii(string folderPath = null, System.Action<string> callBack = null)
    {
        Ookii.Dialogs.VistaFolderBrowserDialog dialog = new Ookii.Dialogs.VistaFolderBrowserDialog();
        // dialog.Description = "请选择文件夹";
        dialog.ShowNewFolderButton = true;
        dialog.SelectedPath = folderPath;

        if (dialog.ShowDialog() == DialogResult.OK)
        {
            callBack?.Invoke(dialog.SelectedPath);
            Debug.Log(dialog.SelectedPath);
        }
    }
    private void SelectFolder_Dll(string folderPath = null, System.Action<string> callBack = null)
    {
        System.Windows.Forms.FolderBrowserDialog dialog = new FolderBrowserDialog();
        // dialog.Description = "请选择文件夹";
        dialog.ShowNewFolderButton = true;
        dialog.RootFolder = Environment.SpecialFolder.MyComputer; //显示文件夹选择框时,默认讲路径定位到我的电脑目录;
        dialog.SelectedPath = folderPath; //跟踪当前位置

        if (dialog.ShowDialog() == DialogResult.OK)
        {
            callBack?.Invoke(dialog.SelectedPath);
            Debug.Log(dialog.SelectedPath);
        }
    }

    private void SelectFolder_Dialog(string folderPath = null, System.Action<string> callBack = null)
    {
        OpenFolderDialog ofn2 = new OpenFolderDialog();

        ofn2.pszDisplayName = new string(new char[2048]); // 存放目录路径缓冲区  
        // ofn2.lpszTitle = "Open Folder Dialog"; // 标题  
        ofn2.ulFlags = 0x00000040; // 新的样式,带编辑框 

        IntPtr pidlPtr = WindowDll.SHBrowseForFolder(ofn2);//打开窗体 返回选中文件

        int count = 2048;
        char[] charArray = new char[count];
        for (int i = 0; i < count; i++)
        {
            charArray[i] = '\0';
        }

        WindowDll.SHGetPathFromIDList(pidlPtr, charArray);//解析数据
        string res = new string(charArray);
        res = res.Substring(0, res.IndexOf('\0'));

        Debug.Log(res);
        callBack?.Invoke(res);
    }

   


    public void OpenFolder(string path)
    {
        System.Diagnostics.Process.Start("explorer.exe", path);
    }
}


//如果这里写成class而不是struct,最后只能获得单文件,不能获得所有文件
//参考链接:https://blog.csdn.net/weixin_39766005/article/details/103705178
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct OpenFileDialog
{
    public int structSize; //结构的内存大小
    public IntPtr dlgOwner; //设置对话框的句柄
    public IntPtr instance; //根据flags标志的设置,确定instance是谁的句柄,不设置则忽略
    public string filter; //调取文件的过滤方式
    public string customFilter; //一个静态缓冲区 用来保存用户选择的筛选器模式
    public int maxCustFilter; //缓冲区的大小
    public int filterIndex; //指向的缓冲区包含定义过滤器的字符串对

    public string file; //存储调取文件路径 
    public int maxFile; //存储调取文件路径的最大长度 至少256
    public string fileTitle; //调取的文件名带拓展名
    public int maxFileTitle; //调取文件名最大长度

    public string initialDir; //最初目录
    public string title; //打开窗口的名字
    public int flags; //初始化对话框的一组位标志  参数类型和作用查阅官方API
    public short fileOffset; //文件名前的长度
    public short fileExtension; //拓展名前的长度
    public string defExt; //默认的拓展名
    public IntPtr custData; //传递给lpfnHook成员标识的钩子子程的应用程序定义的数据
    public IntPtr hook; //指向钩子的指针。除非Flags成员包含OFN_ENABLEHOOK标志,否则该成员将被忽略。
    public string templateName; //模块中由hInstance成员标识的对话框模板资源的名称
    public IntPtr reservedPtr;
    public int reservedInt;
    public int flagsEx; //可用于初始化对话框的一组位标志 
 
    public OpenFileDialog GetOpenFileDialog(string folderPath = null, string filter = null, bool isSave = false)
    {
        OpenFileDialog dialog = this;
        dialog.structSize = Marshal.SizeOf(dialog);
        dialog.filter = filter; // "exe files\0*.exe\0All Files\0*.*\0\0";
        dialog.initialDir = folderPath; //默认路径

        dialog.file = new string(new char[1024]);
        dialog.maxFile = dialog.file.Length;
        dialog.fileTitle = new string(new char[64]);
        dialog.maxFileTitle = dialog.fileTitle.Length;

        //dialog.title = "Open File Dialog";
        //dialog.defExt = "exe";//显示文件的类型

        //注意一下项目不一定要全选 但是0x00000008项不要缺少
        if (!isSave)
        {
            //OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST| OFN_ALLOWMULTISELECT|OFN_NOCHANGEDIR  
            dialog.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;
        }
        else
        {
            dialog.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008;
        }

        return dialog;
    }
}

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct OpenFolderDialog
{
    public IntPtr hwndOwner;
    public IntPtr pidlRoot;
    public String pszDisplayName;
    public String lpszTitle;
    public UInt32 ulFlags;
    public IntPtr lpfn;
    public IntPtr lParam;
    public int iImage;
}

public class WindowDll
{
    [DllImport("user32.dll")]
    public static extern IntPtr GetActiveWindow();

    [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    public static extern bool GetOpenFileName([In, Out] OpenFileDialog dialog); //不能改

    [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    public static extern bool GetSaveFileName([In, Out] OpenFileDialog ofn);


    [DllImport("shell32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    public static extern IntPtr SHBrowseForFolder([In, Out] OpenFolderDialog ofn);

    [DllImport("shell32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    public static extern bool SHGetPathFromIDList([In] IntPtr pidl, [In, Out] char[] fileName);
}
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using UnityEngine;
using UnityEngine.Serialization;

public interface Form
{
    //打开目录、类型筛选、返回数据
    public void SelectFile(string folderPath = null, string filter = null, System.Action<FileData> callBack = null);

    public void SelectSaveFile(string folderPath = null, string filter = null, Action<string, bool> callBack = null);


    public void SelectFolder(string folderPath = null, System.Action<string> callBack = null);

    public void OpenFolder(string path);
}

public struct FileData
{
    public string FolderPath;
    public string[] FilePath;
    public string[] FileName;

    private string fileData;

    public string FileDatas
    {
        set
        {
            fileData = value;
            FolderPath = null;
            FilePath = null;
            FileName = null;


            string[] Splitstr = { "\0" };
            string[] strs = value.Split(Splitstr, StringSplitOptions.RemoveEmptyEntries);
            int len = strs.Length;

            if (len == 1) //文件 全路径
            {
                string path = strs[0].Replace("\\", "/");
                FilePath = new[] { path };
                
                int index = path.LastIndexOf('/');
                FolderPath = path.Substring(0, index);
                
                index++;
                string fileName = path.Substring(index, path.Length - index);
                FileName = new[] { fileName };
            }
            else if (len > 1)
            { 
                len -= 1;
                FolderPath = strs[0].Replace("\\", "/");  //0  文件夹 全路径 
                FileName = new string[len];    //>=1  文件名
                FilePath = new string[len];

                for (int i = 0; i < len; i++)
                {
                    FileName[i] = strs[i + 1];
                    FilePath[i] = FolderPath + "/" + strs[i + 1]; 
                }
            }   
        }
    }

    public string ToString()
    {
        StringBuilder selectFileBuilder = GetStringBuilder(FilePath);
        StringBuilder selectFileNameBuilder = GetStringBuilder(FileName);

        string str =
            $"Folder: {FolderPath}\r\nFile: {selectFileBuilder.ToString()}\r\nFileName: {selectFileNameBuilder.ToString()}";
        Debug.Log(str);
        return str;
    }

    private StringBuilder GetStringBuilder(string[] arr)
    {
        StringBuilder builder = new StringBuilder();
        if (arr != null)
        {
            int len = arr.Length;
            for (int i = 0; i < len; i++)
            {
                builder.AppendLine(arr[i]);
            }
        }

        return builder;
    }
}
public class SystemFormMgr : Singleton<SystemFormMgr>
{

    private Form form_Window;

    public Form SystemForm
    {
        get
        {
            if (form_Window == null)
            {
#if UNITY_STANDALONE_WIN || UNITY_EDITOR
       form_Window = new Form_Window();
#elif UNITY_ANDROID || UNITY_IPHONE
       form_Window = new Form_Android();     
#elif UNITY_IOS
      form_Window = new Form_IOS();   
#endif   
            }
            return form_Window;
        }
    }
}

你可能感兴趣的:(unity,单片机,游戏引擎)