1. 程式人生 > >unity 檔案的建立及讀取

unity 檔案的建立及讀取

 /*
     * path:檔案建立目錄
     * name:檔案的名稱
     *  info:寫入的內容
     */
    public static void CreateFile(string path, string name, string info)
    {
        //檔案流資訊
        StreamWriter sw;
        FileInfo t = new FileInfo(path + "//" + name);


        //如果此檔案不存在則建立
        sw = t.CreateText();


        //以行的形式寫入資訊
        sw.WriteLine(info);
        //關閉流
        sw.Close();
        //銷燬流
        sw.Dispose();
    }


    /*
     * path:讀取檔案的路徑
     * name:讀取檔案的名稱
     */
    public static string LoadFile(string path, string name)
    {
        //使用流的形式讀取
        StreamReader sr = null;
        try
        {
            sr = File.OpenText(path + "//" + name);
        }
        catch (Exception e)
        {
            //路徑與名稱未找到檔案則直接返回空
            return null;
        }
        string arrlist;
        arrlist = sr.ReadLine();
        //關閉流
        sr.Close();
        //銷燬流
        sr.Dispose();
        //將陣列連結串列容器返回
        return arrlist;
    }