You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Unity中如何读写项目文件夹外的TXT文件?已尝试File、StreamWriter、StreamReader及WWW但遇问题求助

Unity读写外部TXT文件问题解决方案

我来帮你搞定这个Unity里读写外部文件的问题,你遇到的这几个坑我都踩过,咱们一步步拆解解决:

1. 路径被自动拼接的问题

你遇到的F:\Project\D:\File.txt这种错误路径,大概率是代码里不小心把绝对路径和Unity项目路径(比如Application.dataPath)拼接在一起了。比如如果写了Application.dataPath + @"D:\File.txt",就会出现这种拼接错误。

解决方法很简单:直接使用完整的绝对路径,不要和任何项目相关路径拼接。比如:

// 正确写法:直接用绝对路径
string targetPath = @"D:\File.txt";

注意路径字符串前加@可以避免转义字符的问题,不用@的话要写成"D:\\File.txt"

2. UnauthorizedAccessException权限异常

这个错误通常是以下几种情况导致的,对应解决方法:

  • 目标目录无读写权限:比如直接写入C盘根目录,Windows的安全机制会阻止。建议换成用户有权限的目录,比如文档文件夹:
    // 获取用户文档目录,再拼接文件名
    string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    string targetPath = Path.Combine(docPath, "File.txt");
    
    或者手动给D:\目录添加读写权限(右键文件夹→属性→安全→编辑,给当前用户添加读写权限)。
  • 文件被其他进程占用:比如你已经用记事本打开了D:\File.txt,此时Unity无法写入,关闭其他占用文件的程序即可。
  • 文件是只读属性:右键文件→属性,取消“只读”勾选。

3. File/StreamWriter/StreamReader的正确用法示例

给你写两个靠谱的读写示例,包含异常处理:

读取文件

using System.IO;
using UnityEngine;

public class FileTest : MonoBehaviour
{
    void Start()
    {
        string targetPath = @"D:\File.txt";
        ReadTextFile(targetPath);
    }

    void ReadTextFile(string path)
    {
        try
        {
            if (File.Exists(path))
            {
                // 使用using自动释放资源
                using (StreamReader reader = new StreamReader(path))
                {
                    string content = reader.ReadToEnd();
                    Debug.Log("读取到的内容:" + content);
                }
            }
            else
            {
                Debug.LogWarning("目标文件不存在:" + path);
            }
        }
        catch (UnauthorizedAccessException ex)
        {
            Debug.LogError("权限不足:" + ex.Message);
        }
        catch (Exception ex)
        {
            Debug.LogError("读取失败:" + ex.Message);
        }
    }
}

写入文件

using System.IO;
using UnityEngine;

public class FileTest : MonoBehaviour
{
    void Start()
    {
        string targetPath = @"D:\File.txt";
        string content = "这是写入的测试内容";
        WriteTextFile(targetPath, content);
    }

    void WriteTextFile(string path, string content)
    {
        try
        {
            // append: false 表示覆盖原有内容,true表示追加内容
            using (StreamWriter writer = new StreamWriter(path, append: false))
            {
                writer.Write(content);
            }
            Debug.Log("写入成功");
        }
        catch (UnauthorizedAccessException ex)
        {
            Debug.LogError("权限不足:" + ex.Message);
        }
        catch (Exception ex)
        {
            Debug.LogError("写入失败:" + ex.Message);
        }
    }
}

4. WWW类的问题(及替代方案)

首先,WWW类已经被Unity弃用了,官方推荐用UnityWebRequest。另外你遇到的cannot convert WWW to string错误,是因为WWW不能直接强制转成字符串,需要访问它的text属性,而且WWW是异步操作,必须等待请求完成。

不推荐的WWW写法(仅作参考)

using UnityEngine;
using System.Collections;

public class WWWTest : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(ReadFileWithWWW());
    }

    IEnumerator ReadFileWithWWW()
    {
        // 本地文件要加file:///前缀
        string url = "file:///" + @"D:\File.txt";
        WWW www = new WWW(url);
        // 等待请求完成
        yield return www;

        if (!string.IsNullOrEmpty(www.error))
        {
            Debug.LogError("读取错误:" + www.error);
        }
        else
        {
            // 访问text属性获取内容
            string content = www.text;
            Debug.Log("读取到的内容:" + content);
        }
    }
}

推荐的UnityWebRequest写法

using UnityEngine;
using UnityEngine.Networking;
using System.Collections;

public class UnityWebRequestTest : MonoBehaviour
{
    void Start()
    {
        StartCoroutine(ReadFileWithUWR());
    }

    IEnumerator ReadFileWithUWR()
    {
        string url = "file:///" + @"D:\File.txt";
        using (UnityWebRequest request = UnityWebRequest.Get(url))
        {
            yield return request.SendWebRequest();

            if (request.result != UnityWebRequest.Result.Success)
            {
                Debug.LogError("读取失败:" + request.error);
            }
            else
            {
                string content = request.downloadHandler.text;
                Debug.Log("读取到的内容:" + content);
            }
        }
    }
}

额外注意事项

  • 在Unity编辑器中测试时,确保杀毒软件或防火墙没有阻止Unity访问外部文件。
  • 打包到移动端(Android/iOS)时,需要额外配置权限:
    • Android:在PlayerSettings里添加WRITE_EXTERNAL_STORAGEREAD_EXTERNAL_STORAGE权限(Android 10+还要考虑Scoped Storage)。
    • iOS:在Info.plist中添加NSDocumentsFolderUsageDescription等权限描述。

内容的提问来源于stack exchange,提问作者hndsmkkgr

火山引擎 最新活动