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;
}      


<script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/ugfdfgg/article/details/86600110