UInity基礎-Unity對TXT文本讀取寫入刪除操作

在Unity開發或者在c#開發中經常會使用txt存儲文本信息,需要對文本進行讀取操作,寫入操作或者是刪除操作。記錄一下。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Text;
using UnityEngine.UI;
public class TxtWrite : MonoBehaviour
{
    public InputField _inputField;

    // Start is called before the first frame update
    void Start()
    {
        //AddTXTText("2測試文本內容");
       // ReadTxt();
    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void Btn_Write()
    {
        string str_input = _inputField.text;
        AddTXTText(str_input);
        ReadTxt();
    }//寫入
     void AddTXTText(string txtText)
    {
        string path = Application.dataPath + "/StreamingAssets/ShoppCart.txt";
        StreamWriter sw;
        FileInfo fi = new FileInfo(path);
        if (!File.Exists(path))
        {
            sw = fi.CreateText();
        }
        else
        {
            sw = fi.AppendText();
        }
        sw.WriteLine(txtText);
        sw.Close();
        sw.Dispose();
        
    }
    //讀取
    void ReadTxt()
    {
        string path = Application.dataPath + "/StreamingAssets/ShoppCart.txt";
        string[] strs = File.ReadAllLines(path);
        foreach (string item in strs)
        {
            print(item);
           // File.Delete(item);
        }
    }
    //刪除
    public  void DeleteTxt()
    {
        string path = Application.dataPath + "/StreamingAssets/ShoppCart.txt";
        File.WriteAllText(path,string.Empty);
        print("成功");
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章