C# Reading of text file stopped working - with Uni

2019-07-10 11:56发布

问题:

I have a program that reads in any amount of .txt files in a directory and assembles them in a list, this list is then displayed to the user one at a time. The user makes a decision at this point and the reaction time is stored. Recently the text import script stopped working for no reason. I haven't changed any of the text import code in months.

I've checked the code that reads in the files and nothing was being recognised at all.

This is part of Unity program just FYI.

TextImport

using UnityEngine;
using System.Collections;
using System.IO;
using System.Collections.Generic;

public class TextImport : MonoBehaviour {

    public static List<string> TextLines;
    bool FileRead = false;

    // Use this for initialization
    void Awake() {
        TextLines = new List<string>();
        string path;
        if(Application.platform == RuntimePlatform.WindowsEditor)
        {
            path = Application.dataPath + "/Resources/";
        }
        else if (Application.platform == RuntimePlatform.WindowsPlayer)
        {
            path = Application.dataPath;
        }
        else if (Application.platform == RuntimePlatform.Android)
        {
            FileRead = true;
            path = "/StroopTest/";
            TextAsset Allfiles = Resources.Load("Android/AllText") as TextAsset;
            string[] AllLinesAndroid = Allfiles.text.Split("\n"[0]);
            foreach (string Line in AllLinesAndroid)
            {
                TextLines.Add(Line);
                break;
            }
        }
        else
        {
            path = Application.dataPath;
        }
        if (!FileRead)
        {
            DirectoryInfo info = new DirectoryInfo(path);
            FileInfo[] fileInfo = info.GetFiles("*.txt");//I've changed the "*.txt" to nothing to read all files instead of just .txt files
            foreach (FileInfo file in fileInfo)
            {
                //I created another List here to store the file names that were read, however none were.
                string[] AllLines = File.ReadAllLines(file.FullName);
                foreach (string line in AllLines)
                {
                    TextLines.Add(line);
                }
            }
        }
    }
}

回答1:

I suggest using Application.persistentDataPath.

Application.dataPath is a read-only directory, where (if packaged to do so) you can find game-related assets there.

Application.persistentDataPath, however, is a writeable directory and returns a path (different for different platforms) where you can add stuff at runtime (ex: writing a file, downloading a file, etc.)

I hope that helps.