首页 > 其他分享 >unity 打开电脑本地文件夹

unity 打开电脑本地文件夹

时间:2023-04-23 14:12:46浏览次数:27  
标签:IntPtr string ofn unity 文件夹 本地 new null public

1.调用方法如下

这是选择路径

 

2.代码如下

using System;
using System.IO;
using System.Runtime.InteropServices;
using UnityEngine;

/// <summary>
/// 调用系统代码,打开本地文件夹
/// </summary>
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class OpenDialogFile
{
    public int structSize = 0;
    public IntPtr dlgOwner = IntPtr.Zero;
    public IntPtr instance = IntPtr.Zero;
    public String filter = null;
    public String customFilter = null;
    public int maxCustFilter = 0;
    public int filterIndex = 0;
    public String file = null;
    public int maxFile = 0;
    public String fileTitle = null;
    public int maxFileTitle = 0;
    public String initialDir = null;
    public String title = null;
    public int flags = 0;
    public short fileOffset = 0;
    public short fileExtension = 0;
    public String defExt = null;
    public IntPtr custData = IntPtr.Zero;
    public IntPtr hook = IntPtr.Zero;
    public String templateName = null;
    public IntPtr reservedPtr = IntPtr.Zero;
    public int reservedInt = 0;
    public int flagsEx = 0;
}

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

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public class OpenFileName
{
    public int structSize = 0;
    public IntPtr dlgOwner = IntPtr.Zero;
    public IntPtr instance = IntPtr.Zero;
    public String filter = null;
    public String customFilter = null;
    public int maxCustFilter = 0;
    public int filterIndex = 0;
    public String file = null;
    public int maxFile = 0;
    public String fileTitle = null;
    public int maxFileTitle = 0;
    public String initialDir = null;
    public String title = null;
    public int flags = 0;
    public short fileOffset = 0;
    public short fileExtension = 0;
    public String defExt = null;
    public IntPtr custData = IntPtr.Zero;
    public IntPtr hook = IntPtr.Zero;
    public String templateName = null;
    public IntPtr reservedPtr = IntPtr.Zero;
    public int reservedInt = 0;
    public int flagsEx = 0;
}

public static class FolderBrowserHelper
{

    #region Window

    [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    private static extern bool GetOpenFileName([In, Out] OpenFileName ofn);

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

    [DllImport("Comdlg32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    private static extern bool GetOpenFileName([In, Out] OpenDialogFile ofn);

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

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

    [DllImport("shell32.dll", SetLastError = true, ThrowOnUnmappableChar = true, CharSet = CharSet.Auto)]
    private static extern bool SHGetPathFromIDList([In] IntPtr pidl, [In, Out] char[] fileName);

    #endregion

    public const string IMAGEFILTER = "图片文件(*.jpg;*.png)\0*.jpg;*.png";
    public const string ALLFILTER = "所有文件(*.*)\0*.*";

    /// <summary>
    /// 选择文件
    /// </summary>
    /// <param name="callback">返回选择文件夹的路径</param>
    /// <param name="filter">文件类型筛选器</param>
    public static void SelectFile(Action<string> callback, string filter = ALLFILTER)
    {
        try
        {
            OpenFileName openFileName = new OpenFileName();
            openFileName.structSize  = Marshal.SizeOf(openFileName);
            // openFileName.initialDir = "初始目录"

            openFileName.filter = filter;
            openFileName.file = new string(new char[256]);
            openFileName.maxFile = openFileName.file.Length;
            openFileName.fileTitle = new string(new char[64]);
            openFileName.maxFileTitle = openFileName.fileTitle.Length;
            openFileName.title = "选择文件";
            openFileName.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000008;
            if (GetSaveFileName(openFileName))
            {
                string filepath = openFileName.file; //选择的文件路径;  
                if (File.Exists(filepath))
                {
                    if (callback != null)
                        callback(filepath);
                    return;
                }
            }
        }
        catch (Exception e)
        {
            Debug.LogError(e);
        }

        if (callback != null)
            callback(string.Empty);
    }

    /// <summary>
    /// 调用WindowsExploer 并返回所选文件夹路径
    /// </summary>
    /// <param name="dialogtitle">打开对话框的标题</param>
    /// <returns>所选文件夹路径</returns>
    public static string GetPathFromWindowsExplorer(string dialogtitle = "请选择下载路径")
    {
        try
        {
            OpenDialogDir ofn2 = new OpenDialogDir();
            ofn2.pszDisplayName = new string(new char[2048]);
            ; // 存放目录路径缓冲区  
            ofn2.lpszTitle = dialogtitle; // 标题  
            ofn2.ulFlags = 0x00000040; // 新的样式,带编辑框  
            IntPtr pidlPtr = SHBrowseForFolder(ofn2);

            char[] charArray = new char[2048];

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

            SHGetPathFromIDList(pidlPtr, charArray);
            string res = new string(charArray);
            res = res.Substring(0, res.IndexOf('\0'));
            return res;
        }
        catch (Exception e)
        {
            Debug.LogError(e);
        }

        return string.Empty;
    }

    /// <summary>
    /// 打开目录
    /// </summary>
    /// <param name="path">将要打开的文件目录</param>
    public static void OpenFolder(string path)
    {
        System.Diagnostics.Process.Start("explorer.exe", path);
    }
}

3.选择一个文件夹,然后把文件夹里面的东西复制到另一个文件夹里面

 /// <summary>
    /// 选择一个文件夹,然后把文件夹里面的东西复制到另一个文件夹里面
    /// </summary>
    /// <param name="sourcePath">选择的路径</param>
    /// <param name="destPath">另一个路径</param>
    public void CopyFolder(string sourcePath, string destPath)
    {
        if (Directory.Exists(sourcePath))
        {
            if (!Directory.Exists(destPath))
            {
                try
                {
                    Directory.CreateDirectory(destPath);
                }
                catch (Exception ex)
                {
                    throw new Exception("创建目标目录失败:" + ex.Message);
                }
            }
            List<string> files = new List<string>(Directory.GetFiles(sourcePath));
            files.ForEach(c =>
            {
                string destFile = Path.Combine(destPath, Path.GetFileName(c));
                File.Copy(c, destFile, true);

            });
            List<string> folders = new List<string>(Directory.GetDirectories(sourcePath));
            folders.ForEach(c =>
            {
                string destDir = Path.Combine(destPath, Path.GetFileName(c));
                CopyFolder(c, destDir);
            });
        }
        else
        {
            throw new DirectoryNotFoundException("源目录不存在!");
        }
    }

4.选择本地文件并打开

/// <summary>
    /// 选择本地文件并打开
    /// </summary>
    public void onRead()
    {     
        OpenFileName ofn = new OpenFileName();

        ofn.structSize = Marshal.SizeOf(ofn);

        ofn.filter = "Excel文件(*.dxf)\0*.dxf";

        ofn.file = new string(new char[256]);

        ofn.maxFile = ofn.file.Length;

        ofn.fileTitle = new string(new char[64]);

        ofn.maxFileTitle = ofn.fileTitle.Length;
        string path = Application.streamingAssetsPath;
        path = path.Replace('/', '\\');
        //默认路径
        ofn.initialDir = path;
        //ofn.initialDir = "D:\\MyProject\\UnityOpenCV\\Assets\\StreamingAssets";
        ofn.title = "Open Project";

        ofn.defExt = "DXF";//显示文件的类型
                           //注意 一下项目不一定要全选 但是0x00000008项不要缺少
        ofn.flags = 0x00080000 | 0x00001000 | 0x00000800 | 0x00000200 | 0x00000008;//OFN_EXPLORER|OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST| OFN_ALLOWMULTISELECT|OFN_NOCHANGEDIR

        if (ofn.file != "")
        {
            if (WindowDll.GetOpenFileName(ofn))
            {
                
                Manager._Instantiate.LoadDXF(ofn.file);
                //print(ofn.file);
                OnClickAdd(ofn.file);
                GameManager.instance_.btn_shengcheng3wei.transform.GetChild(3).gameObject.SetActive(true);
            }
            else
            {
                GameManager.instance_.btn_shengcheng3wei.SetActive(false);

                GameManager.instance_.QuXiaoDaoRuCad();
             
            }
        }
        
    }
选择本地文件并打开

 

标签:IntPtr,string,ofn,unity,文件夹,本地,new,null,public
From: https://www.cnblogs.com/qq2351194611/p/17346353.html

相关文章

  • 关于sql server数据库本地连接失败的问题的解决
    问题描述打开SQLServer使用时,需要连接到本地数据库;但是一直显示连接本地数据库失败;问题解决右键管理->服务与应用程序->服务->找到这个:右键打开它,再次连接,就能够成功运行啦!......
  • Unity框架:JKFrame2.0学习笔记(十)——自动生成资源引用代码(2)
    前言上一篇记录了自动生成资源引用代码的内部实现,主要是针对addressable的资源系统的,为了在加载时不会因为名字写错,加载错,也更加方便的使用addressable加载,这一篇记录下如何使用。如何使用之前看过,在编辑器中添加了工具按钮我们可以在addressable的groups面板上添加几个测试资源我......
  • Win10 资源管理器导航栏设置:显示库,删除6个文件夹和隐藏OneDrive
    如果你和我一样是刚刚从windows7升级到windows10的,我猜你也会发现资源管理器导航栏里略微恼人的变化:库文件不见了,我的电脑里出现了无法隐藏也无法删除的“我的音乐”之类文件(这一个页面里面显示两边也是醉了!),一个懒得使用的Onedrive占据一方。搞掉他!但是好像不是那么简单。花了点时......
  • 喜马拉雅转为本地音频电脑!解锁喜马拉雅音频宝库
    大家好,今天我来给大家介绍一款实用的工具——喜马拉雅音频专辑下载工具! 很多喜马拉雅用户在听完某个专辑后,想将它下载下来,保存到自己的设备中,但是却无法实现。这时候,喜马拉雅音频专辑下载工具就成了非常有用的一款软件。  工具下载:windows版https://jscs.lanzouw.com/i......
  • 推荐一款能将喜马拉雅转为本地音频的工具!
    很多时候我们会有需要将喜马拉雅转为本地音频的需求,也就是将喜马拉雅音频文件下载到电脑本地文件夹里,方便放到其他软件中进行播放。 这里介绍一款能够将喜马拉雅转为本地音频的工具,非常适合小白新手,使用非常的简单。  工具下载:windows版https://jscs.lanzouw.com/i6pPL......
  • 4.电脑文件夹里搜索文件却找不到,明明是有的
    百度的解决方案无效  有效解决方案1.点击查看选项2.将搜索方式下打钩,即可......
  • idea本地编译报错 程序包org.slf4j不存在
    idea本地编译报错程序包org.slf4j不存在 问题描述:从若依官网下载的项目,修改了自己的数据库连接,运行一直报错,如下(怀疑是j依赖包不全导致,期间我清空了本地mavne库重新下载依然不行):  解决办法:  参考如下:主要原因可能有两种情况:1.还是jar包下载失败,或者没有自动......
  • 【Unity】旋转木马
    对三角函数进行实际操作,需要对木马移动进行平滑插值木马起伏采用的Cos函数的周期实现usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;publicclassMerryGoRound:MonoBehaviour{publicTransformnode;publicfloatrudis;......
  • windows连接ubuntu共享文件夹
    安装sambasudoaptinstallsamba编辑配置文件sudovim/etc/samba/smb.conf在末尾加入:[echohye]#smb用户path=/home/echohye/共享文件夹#共享路径available=yeswriteable=yessecurity=sharebrowseable=yesguestok=yes......
  • Rainbond 结合 Jpom 实现云原生 & 本地一体化项目管理
    Jpom是一个简而轻的低侵入式在线构建、自动部署、日常运维、项目运维监控软件。提供了:节点管理:集群节点,统一管理多节点的项目,实现快速一键分发项目文件项目管理:创建、启动、停止、实时查看项目控制台日志,管理项目文件SSH终端:在浏览器中执行SSH终端,方便进行日常运维,记录执......