如何在项目文件夹之外读写txt文件(Unity)

问题描述 投票:0回答:3

我尝试使用 File、StreamWriter 和 StreamReader 以及项目文件夹之外的路径,但它不起作用。它变成了projectPath xternalPath。例如我的项目路径是F:\Project\,我的txt文件在D:\File.txt,Unity自动将我的路径读取为“F:\Project\D:\File.txt”,否则会给出错误消息:未经授权的访问异常

我也尝试使用 WWW,但收到错误消息“无法将 WWW 转换为字符串”

请帮忙

c# unity-game-engine streamreader streamwriter txt
3个回答
2
投票

尝试给出绝对路径而不是相对路径。 例如

var fullPath = "D:\<file-name>.txt";
var content = "testing"; 
File.WriteAllText(fullPath, content );

上面应该将文件写入您的“D:”驱动器。


0
投票

在查阅了各种论坛后,我终于找到了答案。 结果你必须使用绝对路径(就像下面评论中所说的RSF)并取消选中文件夹属性中的“只读”复选框,以避免当你想写入文件时出现未经授权的访问异常


0
投票

您可以使用System.IO包从外部路径读取文本文件内容。在下面的示例中,我们尝试从 Unity 应用程序的

datapath
访问文本/csv 文件。您可以在那里指定所需的位置,以便从该位置读取它。

using UnityEngine;
using System.Collections;
using UnityEngine.UI;
using System.IO;

public class CSVParser : MonoBehaviour 
{
    public string fileName;
    public Text contentArea;

    private char lineSeperater = '\n';
    private char fieldSeperator = ',';

    void Start () 
    {
        ReadData ();
    }
    
    private void ReadData()
    {
        var source = new StreamReader(GetPath() + "/Resources/" + fileName +".csv");
        var fileContents = source.ReadToEnd();
        source.Close();
        var records = fileContents.Split(lineSeperater);

        // TextAsset csvFile = Resources.Load<TextAsset>(fileName);
        // string[] records = csvFile.text.Split (lineSeperater);
        foreach (string record in records)
        {
            string[] fields = record.Split(fieldSeperator);
            foreach(string field in fields)
            {
                contentArea.text += field + "\t";
            }
            contentArea.text += '\n';
        }
    }

    private static string GetPath(){
        #if UNITY_EDITOR
        return Application.dataPath;
        #elif UNITY_ANDROID
        return Application.persistentDataPath;
        #elif UNITY_IPHONE
        return GetiPhoneDocumentsPath();
        #else
        return Application.dataPath;
        #endif
    }

    private static string GetiPhoneDocumentsPath()
    {
        string path = Application.dataPath.Substring(0, Application.dataPath.Length - 5);
        path = path.Substring(0, path.LastIndexOf('/'));
        return path + "/Documents";
    }
}

注意:您可以使用所需的位置值更改

GetPath
返回语句。另外,直接在
StreamReader
类中指定它。

© www.soinside.com 2019 - 2024. All rights reserved.