sing UnityEngine;
using System.Collections;
using System.IO; //需要導入System.IO,主要使用它的File類
public class TextTest : MonoBehaviour {
private string Mytxt; //用來存放文本內容
void Start()
{
Mytxt = ReadFile("C:\\Users\\Admin\\Desktop\\測試\\text.txt",4 ); //txt文件的絕對路徑
print(Mytxt); //輸出驗證
}
//按路徑讀取txt文本的內容,第一個參數是路徑名,第二個參數是第幾行,返回值是sring[]數組
string ReadFile(string PathName, int linenumber)
{
string[] strs = File.ReadAllLines(PathName);//讀取txt文本的內容,返回sring數組的元素是每行內容
if (linenumber == 0)
{
return "";
}
else
{
return strs[linenumber - 1]; //返回第linenumber行內容
}
}
}
2.讀取txt中一行中的幾個字符
test文檔中有
密碼:123
賬號2:45666
string path = @"C:\Users\Administrator\Desktop\test.txt";
public void Read() { string[] s = File.ReadAllLines(path); string ss = s[0]; Debug.Log(ss.Substring(3, 3)); string s1 = s[1]; Debug.Log(s1.Substring(4, 5)); }