Unity C# 网络学习(六)——FTP(二)

Unity C# 网络学习(六)——FTP(二)

一.FTP下载

public class Lesson14 : MonoBehaviour
{
    private void Start()
    {
        NetworkCredential networkCredential = new NetworkCredential("zzs", "zzzsss123");

        FtpWebRequest ftpWebRequest = WebRequest.Create(new Uri("ftp://127.0.0.1/1.jpg")) as FtpWebRequest;
        if (ftpWebRequest == null)
            return;
        ftpWebRequest.Credentials = networkCredential;
        ftpWebRequest.Proxy = null;
        ftpWebRequest.KeepAlive = false;
        ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
        ftpWebRequest.UseBinary = true;

        FtpWebResponse ftpWebResponse = ftpWebRequest.GetResponse() as FtpWebResponse;
        Stream stream = ftpWebResponse?.GetResponseStream();
        if (stream == null)
            return;
        string path = Application.persistentDataPath + "/copy1.jpg";
        using (FileStream fs = new FileStream(path,FileMode.Create))
        {
            byte[] buffer = new byte[1024];
            int len = stream.Read(buffer,0,buffer.Length);
            while (len > 0)
            {
                fs.Write(buffer,0,len);
                len = stream.Read(buffer,0,buffer.Length);
            }
        }
        stream.Close();
        Debug.Log("下载完成!");
    }
}

二.FTP下载封装

1.协程实现

    public void UpLoadFileMono(string fileName, string path, Action action = null)
    {
        StartCoroutine(UpLoadFile(fileName, path, action));
    }
    private IEnumerator UpLoadFile(string fileName, string path, Action action = null)
    {
        NetworkCredential networkCredential = new NetworkCredential(UserName, Password);
        FtpWebRequest ftpWebRequest = WebRequest.Create(new Uri(FtpURL) + fileName) as FtpWebRequest;
        if (ftpWebRequest == null)
            yield break;
        ftpWebRequest.Credentials = networkCredential;
        ftpWebRequest.Proxy = null;
        ftpWebRequest.Method = WebRequestMethods.Ftp.UploadFile;
        ftpWebRequest.KeepAlive = false;
        ftpWebRequest.UseBinary = true;

        Stream ftpRequestStream = ftpWebRequest.GetRequestStream();

        using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
        {
            byte[] buffer = new byte[10240];
            int length = fs.Read(buffer, 0, buffer.Length);
            while (length > 0)
            {
                ftpRequestStream.Write(buffer, 0, length);
                length = fs.Read(buffer, 0, buffer.Length);
                yield return null;
            }
        }
		ftpWebResponse.Close();
        ftpRequestStream.Close();
        action?.Invoke();
    }

2.Task多线程实现

    public async void DownLoadAsync(string downLoadFileName, string outPath, Action action = null)
    {
        await Task.Run(() =>
        {
            NetworkCredential networkCredential = new NetworkCredential(UserName, Password);

            FtpWebRequest ftpWebRequest = WebRequest.Create(new Uri(FtpURL + downLoadFileName)) as FtpWebRequest;
            if (ftpWebRequest == null)
                return;
            ftpWebRequest.Credentials = networkCredential;
            ftpWebRequest.Proxy = null;
            ftpWebRequest.Method = WebRequestMethods.Ftp.DownloadFile;
            ftpWebRequest.KeepAlive = false;
            ftpWebRequest.UseBinary = true;

            FtpWebResponse ftpWebResponse = ftpWebRequest.GetResponse() as FtpWebResponse;
            Stream stream = ftpWebResponse?.GetResponseStream();
            if (stream == null)
                return;
            using (FileStream fs = new FileStream(outPath, FileMode.Create))
            {
                byte[] buffer = new byte[10240];
                int len = stream.Read(buffer, 0, buffer.Length);
                while (len > 0)
                {
                    fs.Write(buffer, 0, len);
                    len = stream.Read(buffer, 0, buffer.Length);
                }
            }
            ftpWebResponse.Close();
            stream.Close();
            action?.Invoke();
        });
    }

三.FTP的其它操作

1.删除文件

    public async void DeleteFile(string deleteFileName,Action<bool> action = null)
    {
        await Task.Run(() =>
        {
            try
            {
                NetworkCredential networkCredential = new NetworkCredential(UserName, Password);

                FtpWebRequest ftpWebRequest = WebRequest.Create(new Uri(FtpURL + deleteFileName)) as FtpWebRequest;
                if (ftpWebRequest == null)
                {
                    action?.Invoke(false);
                    return;                    
                }
                ftpWebRequest.Credentials = networkCredential;
                ftpWebRequest.Proxy = null;
                ftpWebRequest.Method = WebRequestMethods.Ftp.DeleteFile;
                ftpWebRequest.KeepAlive = false;
                ftpWebRequest.UseBinary = true;

                FtpWebResponse ftpWebResponse = ftpWebRequest.GetResponse() as FtpWebResponse;
                if (ftpWebResponse == null)
                {
                    action?.Invoke(false);
                    return;
                }
                action?.Invoke(true);
                ftpWebResponse.Close();
            }
            catch (Exception e)
            {
                action?.Invoke(false);
                Debug.Log("删除文件失败:"+e);
            }
        });
    }

2.获取文件大小

    public async void GetFileSize(string fileName, Action<long> action = null)
    {
        await Task.Run(() =>
        {
            try
            {
                NetworkCredential networkCredential = new NetworkCredential(UserName, Password);

                FtpWebRequest ftpWebRequest = WebRequest.Create(new Uri(FtpURL + fileName)) as FtpWebRequest;
                if (ftpWebRequest == null)
                {
                    action?.Invoke(0);
                    return;                    
                }
                ftpWebRequest.Credentials = networkCredential;
                ftpWebRequest.Proxy = null;
                ftpWebRequest.Method = WebRequestMethods.Ftp.GetFileSize;
                ftpWebRequest.KeepAlive = false;
                ftpWebRequest.UseBinary = true;

                FtpWebResponse ftpWebResponse = ftpWebRequest.GetResponse() as FtpWebResponse;
                if (ftpWebResponse == null)
                {
                    action?.Invoke(0);
                    return;
                }
                action?.Invoke(ftpWebResponse.ContentLength);
                ftpWebResponse.Close();
            }
            catch (Exception e)
            {
                action?.Invoke(0);
                Debug.Log("获取文件大小失败:"+e);
            }
        });
    }

3.创建文件夹

    public async void CreateDir(string dirName, Action<bool> action = null)
    {
        await Task.Run(() =>
        {
            try
            {
                NetworkCredential networkCredential = new NetworkCredential(UserName, Password);

                FtpWebRequest ftpWebRequest = WebRequest.Create(new Uri(FtpURL + dirName)) as FtpWebRequest;
                if (ftpWebRequest == null)
                {
                    action?.Invoke(false);
                    return;                    
                }
                ftpWebRequest.Credentials = networkCredential;
                ftpWebRequest.Proxy = null;
                ftpWebRequest.Method = WebRequestMethods.Ftp.MakeDirectory;
                ftpWebRequest.KeepAlive = false;
                ftpWebRequest.UseBinary = true;

                FtpWebResponse ftpWebResponse = ftpWebRequest.GetResponse() as FtpWebResponse;
                if (ftpWebResponse == null)
                {
                    action?.Invoke(false);
                    return;
                }
                action?.Invoke(true);
                ftpWebResponse.Close();
            }
            catch (Exception e)
            {
                action?.Invoke(false);
                Debug.Log("创建文件夹失败:"+e);
            }
        });
    }

4.获取文件列表

    public async void GetDirList(string dirName, Action<List<string>> action = null)
    {
        //记得文件夹名称后面要加'/'
        //记得文件夹名称后面要加'/'
        //记得文件夹名称后面要加'/'
        await Task.Run(() =>
        {
            try
            {
                NetworkCredential networkCredential = new NetworkCredential(UserName, Password);
                string p = FtpURL + dirName +"/";
                FtpWebRequest ftpWebRequest = WebRequest.Create(new Uri(p)) as FtpWebRequest;
                if (ftpWebRequest == null)
                {
                    action?.Invoke(null);
                    return;                    
                }
                ftpWebRequest.Credentials = networkCredential;
                ftpWebRequest.Proxy = null;
                ftpWebRequest.Method = WebRequestMethods.Ftp.ListDirectory;
                ftpWebRequest.KeepAlive = false;
                ftpWebRequest.UseBinary = true;

                FtpWebResponse ftpWebResponse = ftpWebRequest.GetResponse() as FtpWebResponse;
                if (ftpWebResponse == null)
                {
                    action?.Invoke(null);
                    return;
                }
                Stream s = ftpWebResponse.GetResponseStream();
                if (s == null)
                {
                    action?.Invoke(null);
                    return;
                }
                
                List<string> res = new List<string>();
                using (StreamReader sr = new StreamReader(s))
                {
                    string str = sr.ReadLine();
                    while (str != null)
                    {
                        res.Add(str);
                        str = sr.ReadLine();
                    }
                }
                s.Close();
                action?.Invoke(res);
                ftpWebResponse.Close();
            }
            catch (Exception e)
            {
                action?.Invoke(null);
                Debug.Log("获取文件列表失败:"+e);
            }
        });
    }
  • 其余操作同理
### 实现 UnityFTP 功能 为了在 Unity 中实现 FTP 文件传输功能,需要编写 C# 脚本来管理与 FTP 服务器的交互。这通常涉及创建一个专门负责处理 FTP 请求的类 `FtpManager`。 #### 创建 FtpManager 类 该类应具备初始化方法以及上传和下载文件的方法。下面展示了一个简单的 `FtpManager` 的结构: ```csharp using UnityEngine; using System.IO; using System.Net; public class FtpManager : MonoBehaviour { private string ftpServerIP = "ftp://yourserverip/"; private string username = "username"; private string password = "password"; public void UploadFile(string localFilePath, string remoteFileName){ try { WebClient client = new WebClient(); client.Credentials = new NetworkCredential(username, password); byte[] fileData = File.ReadAllBytes(localFilePath); MemoryStream stream = new MemoryStream(fileData); string uriString = Path.Combine(ftpServerIP, remoteFileName); client.UploadData(uriString, "STOR", fileData); Debug.Log("Upload Complete"); } catch (Exception e) { Debug.LogError(e.Message); } } } ``` 此代码片段展示了如何定义一个名为 `UploadFile` 方法来完成文件上传操作[^1]。注意这里使用了 `WebClient` 对象来进行实际的数据交换,并通过设置其凭证属性 (`Credentials`) 来验证身份认证信息。 对于用户提到的具体案例——即从本地磁盘位置 `"F:\ClassResources\致青春.jpeg"` 向远程 FTP 站点根目录上传图像文件,则只需调用上述函数并传入相应参数即可。 另外,在场景中还需要配置 UI 组件以便触发这些动作。按照描述中的指示建立好 GameObject 和 Button 并关联至脚本字段之后,当点击按钮时就会自动发起一次新的 FTP 请求尝试将指定路径下的文件发送出去。 最后值得注意的是,虽然这段程序能够满足基本需求,但在生产环境中应当考虑更多因素比如错误处理机制、进度条显示等用户体验优化措施,同时也建议加密敏感信息防止泄露风险。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值