Unity3d读写文件操作

// Use this for initialization
 void Start ()
 {
    string path="";
    if(Application.platform==RuntimePlatform.Android)
    {
       path=Application.persistentDataPath;
    }
    else if(Application.platform==RuntimePlatform.WindowsPlayer)
    {
       path=Application.dataPath;
    }
    else if(Application.platform==RuntimePlatform.WindowsEditor)
    {
       path=Application.dataPath;
    }
  
    string configip=LoadFile(path,"test.txt");
    if(configip!="error")
    {
       gameObject.GetComponent<UILabel>().text="read:"+configip;
    }
    else
    {
       createORwriteConfigFile(path,"test.txt","192.168.200.252");
       string str=LoadFile(path,"test.txt");
       gameObject.GetComponent<UILabel>().text="create:"+str;
    }
 }
 /// <summary>
 /// 在指定位置创建文件   如果文件已经存在则追加文件内容
 /// </summary>
 /// <param name='path'>
 /// 路径
 /// </param>
 /// <param name='name'>
 /// 文件名
 /// </param>
 /// <param name='info'>
 /// 文件内容
 /// </param>
 private void createORwriteConfigFile(string path,string name,string info)
 {
    StreamWriter sw;          
    FileInfo t = new FileInfo(path+"//"+ name);          
    if(!t.Exists)          
    {            
       sw = t.CreateText();
    }          
    else      
    {
       sw = t.AppendText();         
    } 
    sw.WriteLine(info);
    sw.Close();
    sw.Dispose();
 }
 /// <summary>
 /// 删除文件
 /// </summary>
 /// <param name='path'>
 /// Path.
 /// </param>
 /// <param name='name'>
 /// Name.
 /// </param>
 void DeleteFile(string path,string name)
 {
    File.Delete(path+"//"+ name);
 } 
 /// <summary>
 /// 读取文件内容  仅读取第一行
 /// </summary>
 /// <param name='path'>
 /// Path.
 /// </param>
 /// <param name='name'>
 /// Name.
 /// </param>
private string LoadFile(string path,string name)   
{     
    FileInfo t = new FileInfo(path+"//"+ name);          
    if(!t.Exists)
    {
       return "error";
    }
    StreamReader sr =null;    
    sr = File.OpenText(path+"//"+ name);
       string line;    
    while ((line = sr.ReadLine()) != null)    
    {    
    break;
    }
    sr.Close();
    sr.Dispose();
    return line;
}      

posted @ 2013-06-06 15:01  silent  阅读(15965)  评论(0编辑  收藏  举报