Unity3d read and write file operations

// 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>

 /// In the specified location to create the file     if the file already exists in the additional file content

 /// </summary>

 /// <param name='path'>

 /// Route

 /// </param>

 /// <param name='name'>

 /// File name

 /// </param>

 /// <param name='info'>

 /// The contents of the file

 /// </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>

 /// Delete files

 /// </summary>

 /// <param name='path'>

 /// Path.

 /// </param>

 /// <param name='name'>

 /// Name.

 /// </param>

 void DeleteFile(string path,string name)

 {

    File.Delete(path+"//"+ name);

 } 

 /// <summary>

 /// Read the contents of the file   read only the first row

 /// </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 by Barry at November 15, 2013 - 9:56 PM