unity本地和网络文件的读取

测试都是没有问题的,直接引用即可。

包括本地文件的读取,网络文件的读取,截图等比较入门的代码。

using System;
using System.Collections;
using System.Diagnostics;
using System.IO;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;
using UnityEngine.Video;


/// 
/// 本地和网络文件的操作
/// 
/// 

public class MyFile : MonoBehaviour
{
    //public static MyFile _instance;//设置成静态类
    /// 
    /// 导入本地图片
    /// 
    /// 
    /// 
    public void Read_Image(Image image, string url)
    {
        //byte[] buffer;//定义一个二进制数组
        //using (FileStream fileRead1 = new FileStream(url, FileMode.Open, FileAccess.Read))//创建一个数据流
        //{
        //   
        //
        //    buffer = new byte[fileRead1.Length];//创建一个二进制数组,作为文件读取的缓冲区
        //    fileRead1.Read(buffer, 0, buffer.Length);//用数据流,把文件读取到buffer的二进制数组中
        //}
        byte[] buffer = File.ReadAllBytes(url);//,创建一个缓冲区,把url对应的文件以二进制的方式读取进来

        Vector2 v = image.gameObject.GetComponent().sizeDelta;//获取照片的宽和高的Vector2;
        int w = (int)v.x;//提取image的宽度值赋值给w
        int h = (int)v.y;//提取image的高度值赋值给h
        Texture2D texture = new Texture2D(w, h, TextureFormat.RGB24, false);//创建一个空的贴图texture
        texture.LoadImage(buffer);//把缓冲区中德二进制文件赋值给贴图
        Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));//把贴图赋值给新建的sprite
        image.sprite = sprite;//把赋值的Sprite赋值给image,最终实现图片的导入
                                //return sprite;
    }


    /// 
    /// 导入本地音频给播放器
    /// 
    /// 
    /// 
    public void Read_Audio(string url, AudioSource audioSource)
    {
        byte[] buffer = File.ReadAllBytes(url);//,创建一个缓冲区,把url对应的文件以二进制的方式读取进来
        float[] sounddata = new float[buffer.Length / 2];
        for (int i = 0; i < sounddata.Length; i++)
        {
            short s;
            if (BitConverter.IsLittleEndian)
                s = (short)((buffer[i * 2 + 1] << 8) | buffer[i * 2]);
            else
                s = (short)((buffer[i * 2] << 8) | buffer[i * 2 + 1]);
            sounddata[i] = s / 32768.0F;
        }
        float[] clipData = sounddata;//进行数据转换。将byte转成AudioClip可读取的float
        audioSource.clip = AudioClip.Create("audioClip", 16000 * 10, 1, 16000, false);//不进行这一步,audioSource.clip会报空!
        audioSource.clip.SetData(clipData, 0);//完成赋值
                                                //audioSource.Play();//播放
    }


    /// 
    /// 导入本地或网络视频给播放器
    /// 
    /// 
    /// 
    public void Read_Video(string url, VideoPlayer videoplayer)
    {
        videoplayer.url = url;//把播放地址赋值给播放器
                                //videoplayer.Play();//播放
    }


    /// 
    /// 导入网络图片方法1
    /// 
    /// 
    /// 
    public void DownLoad_Image_www(Image image, string url)
    {

        IEnumerator DownLoad_image()
        {
            WWW www = new WWW(url);
            yield return www;
            if (www != null && string.IsNullOrEmpty(www.error))
            {

                Texture2D texture = www.texture;
                image.sprite = Sprite.Create(
                        texture,
                        new Rect(0, 0, texture.width, texture.height),
                        new Vector2(0.5f, 0.5f));
            }
        }
        StartCoroutine(DownLoad_image());//启动协程
    }


    /// 
    /// 导入网络图片方法2
    /// 
    /// 
    /// 
    public void DownLoad_Image(Image image, string url)
    {
        IEnumerator LoadImage()
        {
            using (UnityWebRequest webRequest = new UnityWebRequest())
            {
                //设置URL
                webRequest.url = url;
                //设置访问方式
                webRequest.method = UnityWebRequest.kHttpVerbGET;
                //设置下载类型
                DownloadHandlerTexture DownloadHandlerTexture = new DownloadHandlerTexture(true);
                webRequest.downloadHandler = DownloadHandlerTexture;

                //协程等待
                yield return webRequest.SendWebRequest();

                if (webRequest.isNetworkError || webRequest.isHttpError)
                {
                    UnityEngine.Debug.Log(webRequest.error);//报错
                }
                else
                {
                    //将图片加载到3D平面
                    //plane.GetComponent().material.mainTexture =
                    // DownloadHandlerTexture.GetContent(webRequest);
                    //将图片加载到UI图片
                    Texture2D texture2D = DownloadHandlerTexture.GetContent(webRequest);//把下载的Texture数据赋值给指定的贴图文件
                    Sprite sprite = Sprite.Create(texture2D, new Rect(0, 0, texture2D.width, texture2D.height),new Vector2(0.5f, 0.5f));//把赋值的贴图文件赋值给sprite
                    image.sprite = sprite;//把赋值的Sprite赋值给image,最终实现图片的导入
                }
            }

        }

        StartCoroutine(LoadImage());//启动协程

    }


    /// 
    /// 导入网络图片方法3
    /// 
    /// 
    /// 
    public void DownLoad_Image_byte(Image image, string url)
    {
        IEnumerator LoadImage()
        {
            using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
            {
              
                //协程等待
                yield return webRequest.SendWebRequest();

                if (webRequest.isNetworkError || webRequest.isHttpError)
                {
                    UnityEngine.Debug.Log(webRequest.error);
                }
                else
                {

                    byte[] bs = webRequest.downloadHandler.data;//把下载的数据传给二进制数组

                    Vector2 v = image.gameObject.GetComponent().sizeDelta;//获取照片的宽和高的Vector2;
                    int w = (int)v.x;//提取image的宽度值赋值给w
                    int h = (int)v.y;//提取image的高度值赋值给h
                    Texture2D texture = new Texture2D(w, h, TextureFormat.RGB24, false);//创建一个空的贴图texture
                    texture.LoadImage(bs);//把缓冲区中的二进制文件赋值给贴图
                    Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));//把贴图赋值给新建的sprite
                    image.sprite = sprite;//把赋值的Sprite赋值给image,最终实现图片的导入
                }
            }

        }
        StartCoroutine(LoadImage());//启动协程
    }


    /// 
    /// 导入网络音频方法1
    /// 
    /// 
    /// 
    public void DownLoad_Audio_www(AudioSource audioSource, string url)
    {
        IEnumerator DownLoad_audio()
        {
            WWW www = new WWW(url);
            yield return www;
            if (www != null && string.IsNullOrEmpty(www.error))
            {
                AudioClip clip = www.GetAudioClip();
                audioSource.clip = clip;
                //audioSource.Play();
            }
        }

        StartCoroutine(DownLoad_audio());//启动协程
    }


    /// 
    /// 导入网络音频方法2
    /// 
    /// 
    /// 
    public void DownLoad_Audio_Byte(AudioSource audioSource, string url)
    {
        IEnumerator LoadAudio()
        {
            using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
            {
                //设置URL
                //webRequest.url = url;
                //设置访问方式
                //webRequest.method = UnityWebRequest.kHttpVerbGET;
                //设置下载类型
                //webRequest.downloadHandler = new DownloadHandlerBuffer();

                //协程等待
                yield return webRequest.SendWebRequest();

                if (webRequest.isNetworkError || webRequest.isHttpError)
                {
                    UnityEngine.Debug.Log(webRequest.error);
                }
                else
                {

                    byte[] buffer = webRequest.downloadHandler.data;//把下载的数据装入二进制数组
                    float[] sounddata = new float[buffer.Length / 2];
                    for (int i = 0; i < sounddata.Length; i++)
                    {
                        short s;
                        if (BitConverter.IsLittleEndian)
                            s = (short)((buffer[i * 2 + 1] << 8) | buffer[i * 2]);
                        else
                            s = (short)((buffer[i * 2] << 8) | buffer[i * 2 + 1]);
                        sounddata[i] = s / 32768.0F;
                    }
                    float[] clipData = sounddata;//进行数据转换。将byte转成AudioClip可读取的float
                    audioSource.clip = AudioClip.Create("audioClip", 16000 * 10, 1, 16000, false);//不进行这一步,audioSource.clip会报空!
                    audioSource.clip.SetData(clipData, 0);//完成赋值
                    //audioSource.Play();//播放
                }
            }

        }
        StartCoroutine(LoadAudio());//启动协程
    }


    /// 
    /// 导入网络音频方法3
    /// 
    /// 
    /// 
    public void DownLoad_Audio(AudioSource audioSource, string url)
    {
        IEnumerator LoadImage()
        {
            using (UnityWebRequest webRequest = new UnityWebRequest(url))
            {
                //设置URL
                // webRequest.url = url;
                //设置访问方式
                webRequest.method = UnityWebRequest.kHttpVerbGET;
                //设置下载类型
                DownloadHandlerAudioClip DownloadHandlerAudioClip = new DownloadHandlerAudioClip(url, AudioType.WAV);
                webRequest.downloadHandler = DownloadHandlerAudioClip;

                //协程等待
                yield return webRequest.SendWebRequest();

                if (webRequest.isNetworkError || webRequest.isHttpError)
                {
                    UnityEngine.Debug.Log(webRequest.error);
                }
                else
                {
                    audioSource.clip = DownloadHandlerAudioClip.GetContent(webRequest);
                    //audioSource.Play();//播放
                }
            }

        }

        StartCoroutine(LoadImage());//启动协程

    }


    /// 
    /// 下载文件到本地方法1(速度慢)
    /// 
    /// 
    /// 

    public void DwonLoad_www(string url, string url2)
    {
        IEnumerator dwonLoad()
        {
            WWW www = new WWW(url);
            if (www != null && string.IsNullOrEmpty(www.error))
            {
                while (!www.isDone)
                {
                    print(www.progress);//打印下载进度
                }
                if (www.isDone)
                {
                    print("完成下载");
                }
            }
            yield return www;

            if (!File.Exists(url2))//如果url2文件不存在
            {
                File.WriteAllBytes(url2, www.bytes);
            }
            else if (File.Exists(url2))//如果url2文件存在
            {
                print("文件已经存在");
            }
                
        }
        StartCoroutine(dwonLoad());//启动协程
    }


    /// 
    /// 下载文件到本地方法2
    /// 
    /// 
    /// 
    public void DwonLoad(string url, string url2)
    {
            
        IEnumerator dwonload()
        {
               
            using (UnityWebRequest webRequest = UnityWebRequest.Get(url))
            {
                //协程等待
                webRequest.SendWebRequest();

                if (webRequest.isNetworkError || webRequest.isHttpError)
                {
                    UnityEngine.Debug.Log(webRequest.error);//报错
                }
                else
                {
                    while (!webRequest.isDone)//循环,直到下载完成
                    {

                        print(webRequest.downloadProgress);//打印下载进度
                        yield return 0;//返回自己,每帧执行
                    }
                    if (webRequest.isDone) //如果下载完成了
                    {
                        print("完成");

                    }

                    byte[]  bs = webRequest.downloadHandler.data;//把下载的数据存储成二级制数组

                    //把二级制数字写入相应的位置
                    if (!File.Exists(url2))//如果url2文件不存在
                    {
                        File.WriteAllBytes(url2, bs);//如果url2文件存在
                    }
                    else if(File.Exists(url2)){
                        print("文件已经存在");
                    }
                       

                    //把二级制数字写入相应的位置
                    //using (FileStream filewrite = new FileStream(url2, FileMode.Create, FileAccess.Write))
                    //{
                    //    filewrite.Write(bs, 0, bs.Length);
                    //}
                }

            }
                
        }

        StartCoroutine(dwonload());//启动协程
    }



    /// 
    /// 截图
    /// 
    /// 
    public void Jt(Rect rect, string url)
    {
        IEnumerator MyCaptureScreen()
        {

            yield return new WaitForEndOfFrame();
            Texture2D texture = new Texture2D((int)rect.width, (int)rect.height, TextureFormat.RGB24, false);
            texture.ReadPixels(source: rect, 0, 0);
            texture.Apply();
            Texture_write_Png(url, texture);
            //Texture_write_Png(Application.dataPath + "wz", texture);
            //Texture_write_Png("/Volumes/project/aa/Screenshot.png", texture);

        }
        StartCoroutine(MyCaptureScreen());//启动协程

    }

    /// 
    /// 把Texture写入png文件
    /// 
    /// 
    /// 
    /// 
    public bool Texture_write_Png(string url, Texture2D texture)

    {

        byte[] buffer = texture.EncodeToPNG();//把二维贴图转换成PNG格式的二进制数组
        File.WriteAllBytes(url, buffer);//把二进制数组的数据写入url对应的文件
                                        //using (FileStream filewrite = new FileStream(url, FileMode.Create, FileAccess.Write ))//创建一个数据流
                                        //{

        //    buffer = texture.EncodeToPNG();//把二维贴图转换成PNG格式的二进制数组
        //    filewrite.Write(buffer, 0, buffer.Length);//用数据流,把二进制数组的数据写入url对应的文件

        //}

        return true;

    }

    /// 
    /// 把Texture写入png文件
    /// 
    /// 
    /// 
    /// 
    public bool Texture_write_Jpg(string url, Texture2D texture)

    {
        if (url == null)
        {
            print("没有输入导入贴图的路径");
        }
        using (FileStream filewrite = new FileStream(url, FileMode.Create, FileAccess.Write))
        {

            byte[] buffer = texture.EncodeToJPG();
            filewrite.Write(buffer, 0, buffer.Length);
        }

        return true;
    }

    /// 
    /// 把Texture写入png文件
    /// 
    /// 
    /// 
    /// 
    public bool Texture_write_Tga(string url, Texture2D texture)

    {
        if (url == null)
        {
            print("没有输入导入贴图的路径");
        }
        using (FileStream filewrite = new FileStream(url, FileMode.Create, FileAccess.Write))
        {

            byte[] buffer = texture.EncodeToTGA();
            filewrite.Write(buffer, 0, buffer.Length);
        }

        return true;
    }

    /// 
    /// 把Texture写入png文件
    /// 
    /// 
    /// 
    /// 
    public bool Texture_write_Exr(string url, Texture2D texture)

    {
        if (url == null)
        {
            print("没有输入导入贴图的路径");
        }
        using (FileStream filewrite = new FileStream(url, FileMode.Create, FileAccess.Write))
        {

            byte[] buffer = texture.EncodeToEXR();
            filewrite.Write(buffer, 0, buffer.Length);
        }

        return true;
    }






    //打开和关闭外部程序
    //---------------------------------------------------------------------------------------------------------------------
    //
    /// 
    /// 开启外部程序或本地网页
    /// 
    /// 
    public void StartExe(string url)
    {
        ProcessStartInfo processStartInfo = new ProcessStartInfo();
        processStartInfo.FileName = url;
        //processStartInfo.Arguments = "启动 程序 1 2  3
        Process.Start(processStartInfo);
    }

    /// 
    /// 关闭外部程序
    /// 
    /// 
    public void KillProcess(string processName)
    {
        Process[] processes = Process.GetProcesses();
        foreach (Process process in processes)
        {
            try
            {
                if (!process.HasExited)
                {
                    if (process.ProcessName == processName)
                    {
                        process.Kill();
                        UnityEngine.Debug.Log("已关闭进程");
                    }
                }
            }
            catch (System.InvalidOperationException ex)
            {
                UnityEngine.Debug.Log(ex);
            }
        }
    }

    /// 
    /// 打开外部网页
    /// 
    /// 
    public void StartHtml(string url)
    {
        Application.OpenURL(url);
    }






    //文件夹和文件的相关操作
    //--------------------------------------------------------------------------------------------------------------------------------------------------------------
    /// 
    /// 文件夹操作
    /// 
    public void File_Cteat(string myPath)
    {
        DirectoryInfo info = new DirectoryInfo(@myPath);//实例目录

        if (!info.Exists)//判断路径中是否有文件夹,如果没有,则创建文件夹
        {
            info.Create();//创建文件夹
        }


        string myPath02 = Path.Combine(@myPath, @"cc");//定义一个目录,用Path类中的Combine方法衔接
        DirectoryInfo info02 = new DirectoryInfo(myPath02);//实例目录
        if (!info02.Exists)//判断路径中是否有文件夹,如果没有,则创建文件夹
        {
            info02.Create();//创建文件夹
        }

        if (info02.Exists)//判断路径中是否有文件夹,如果有,则删除文件夹
        {
            info02.Delete(true);//删除文件夹
        }


        if (!Directory.Exists(@myPath))//判断路径中是否有文件夹,如果没有,则创建文件夹
        {
            Directory.CreateDirectory(@myPath);//创建文件夹
        }

        if (Directory.Exists(@myPath))//判断路径中是否有文件夹,如果有,则删除文件夹
        {
            Directory.Delete(@myPath);//删除文件夹
        }

    }

    /// 
    /// 文件夹copy
    /// 
    /// 
    public void File_Copy(string filePath)
    {
        //1.在D盘创建一个名字为Directory的文件夹,并创建一个file01.txt文件。
        string dirPath = Path.GetDirectoryName(@filePath);//取得目录的名称
        if (!Directory.Exists(dirPath))//判断目录是否存在,如果目录不存在。则创建目录
        {
            Directory.CreateDirectory(dirPath);//创建目录
        }

        if (!File.Exists(@filePath))//判断文件是否存在,如果不存在。则创建文件
        {
            File.Create(@filePath);
        }

        //2.(先在D盘放一个file02.txt文件)判断若存在,复制到指定的文件夹下
        if (File.Exists(@"/Volumes/project/file02.txt"))
        {
            File.Copy(@"/Volumes/project/file02.txt", @"/Volumes/project/aa/file02.1.txt", true);
        }

        //3.通过脚本打印出指定文件夹下所有子文件夹的目录名
        string[] path = Directory.GetDirectories(@"/Volumes/project/aa");//获取指定目录下子文件夹的名字
        string[] path2 = Directory.GetFiles(@"/Volumes/project/aa");//获取指定目录下子文件的名字
                                                                    //打印获取的目录
        foreach (var dirName in path)
        {
            Console.WriteLine(dirName);
        }
        foreach (var dirName2 in path2)
        {
            Console.WriteLine(dirName2);
        }
    }

    /// 
    /// 把文字写入文件里
    /// 
    /// 
    public void File_WriteText(string filePath3)
    {

        if (File.Exists(@filePath3))//把内容写入文件
        {
            File.WriteAllText(@filePath3, " Hello aaaaaaa");//写入一段文本内容
        }
        string file = File.ReadAllText(@filePath3);//读取文本内容

        //把数组写入文件
        string[] f = new string[] { "Hello", "Hi~", "hhhh" };//定义一个数组
        if (File.Exists(@filePath3))//如果文件存在
        {
            File.WriteAllLines(@filePath3, f);//把数组的内容写入指定的文件
        }

        string[] file_s = File.ReadAllLines(@filePath3);
        foreach (string read in file_s)
        {
            Console.WriteLine("读到的内容 : " + read);
        }
    }


    /// 
    /// 剪切文件
    /// 
    /// 
    /// 
    public void File_Move(string filePath4, string filePathTo4)
    {

        string dirPath = Path.GetDirectoryName(@filePath4);//取得路径中目录的名称
        if (!Directory.Exists(dirPath)) //如果文件不存在,则创建
        {
            Directory.CreateDirectory(dirPath);//创建文件
        }

        if (!File.Exists(@filePath4))//如果文件夹不存在,则创建
        {
            File.Create(@filePath4);//创建文件夹
        }

        //剪切文件 新路径:
        string newFilePath = Path.Combine(@filePathTo4, Path.GetFileName(@filePath4));//用@filePathTo4的路径,@filePath4的文件名,定义新的文件路径
        if (!Directory.Exists(@filePathTo4))//如果文件夹不存在,则创建
        {
            Directory.CreateDirectory(@filePathTo4);//创建文件夹
        }

        if (!File.Exists(newFilePath))//如果文件夹不存在
        {

            File.Move(@filePath4, newFilePath);//把文件剪切到新的文件夹
        }
    }

}


你可能感兴趣的:(unity,unity,游戏引擎,c#)