Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Can we use System.IO and other .NET classes?

Discussion in 'iOS and tvOS' started by TouchSoft, Oct 28, 2008.

  1. TouchSoft

    TouchSoft

    Joined:
    Oct 18, 2008
    Posts:
    218
    I would like to use javascript to import System.IO class into my script so that I can read and write XML files.

    Does the iPhone support using .NET classes in my scripts? Here's an example script:

    Reading a file:

    Code (csharp):
    1.  
    2.    import System;
    3.    import System.IO;
    4.  
    5.    if(File.Exists(file))
    6.    {
    7.       var sr = File.OpenText(file);
    8.       var line = sr.ReadLine();
    9.       while(line != null)
    10.       {
    11.          Debug.Log(line); // prints each line of the file
    12.          line = sr.ReadLine();
    13.       }    
    14.    }
    15.    else
    16.    {
    17.       Debug.Log("Could not Open the file: " + file + " for reading.");
    18.       return;
    19.    }
    20.  
     
  2. TouchSoft

    TouchSoft

    Joined:
    Oct 18, 2008
    Posts:
    218
    Just tested it and yup it works... I was able to write an XML file to the iPhone documents directory.. then read it.

    To be honest.. it was much easier to do in Unity than it is to do in cocoa .. isn't that strange? lol.

    Here's the code I use to read/write ... PS. borrowed some of the code from jakkovanhunen.

    Importing the classes
    Code (csharp):
    1. import System;
    2. import System.IO;
    Reading a file
    Code (csharp):
    1. function ReadFile(file : String)
    2. {  
    3.    if(File.Exists(file))
    4.    {
    5.       var sr = File.OpenText(file);
    6.       var line = sr.ReadLine();
    7.       while(line != null)
    8.       {
    9.         Debug.Log(line); // prints each line of the file
    10.          line = sr.ReadLine();
    11.       }    
    12.    }
    13.    else
    14.    {
    15.       Debug.Log("Error opening: " + file + " for reading.");
    16.       return;
    17.    }
    18. }
    Writing a file
    Code (csharp):
    1. function WriteFile (file : String)
    2. {;
    3.    
    4.     if (File.Exists(file))
    5.     {
    6.         Debug.Log(file+" already exists.");
    7.         return;
    8.     }
    9.    
    10.     var sr = File.CreateText(file);
    11.     sr.WriteLine ("This is my file.");
    12.     sr.WriteLine ("I can write ints {0} or floats {1}, and so on.", 1, 4.2);
    13.     sr.Close();
    14. }
    as jakkovanhunen mentioned in his code.. getting the iPhone's writable documents directory is a little tricky .. here's the code.

    Code (csharp):
    1. private var docPath : String = Application.dataPath;
    2.  
    3. function Awake ()
    4. {
    5.    if(!Application.isEditor)
    6.    {
    7.         docPath = docPath.Substring(0, docPath.Length - 4) + "Documents";
    8.    }
    9.  
    10.    ReadFile(docPath + "/MyFile.xml");
    11. }
    Basically what the code above is saying: If this isn't playing in the editor then adjust the dataPath string to point to the iPhone's "Documents" path.
     
  3. christopherbrown

    christopherbrown

    Joined:
    Oct 19, 2009
    Posts:
    83
    Where in my Unity project would I place an XML file to be accessed and read?
     
  4. prime31

    prime31

    Joined:
    Oct 9, 2008
    Posts:
    6,426
    .NET easier than Cocoa? Not in my opinion. C# is MUCH more verbose most certainly but is it easier? I guess it depends on your definition of the word.

    Read File:
    Code (csharp):
    1. NSString *fileContents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
    Write File:
    Code (csharp):
    1. [fileContents writeToFile:filePath atomically:NO encoding:NSUTF8StringEncoding error:NULL];
     
  5. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    there the 30 lines to load that content in a usable way into unity missing though ;)
     
  6. andeeeee

    andeeeee

    Joined:
    Jul 19, 2005
    Posts:
    8,768
    You can place an XML file in the assets folder (but give it a .txt suffix) and it will be interpreted by Unity as a TextAsset.
     
  7. christopherbrown

    christopherbrown

    Joined:
    Oct 19, 2009
    Posts:
    83
    Thanks for the direction, andeeee.
     
  8. christopherbrown

    christopherbrown

    Joined:
    Oct 19, 2009
    Posts:
    83
    I'm having a lot of trouble with this one, surely due to ignorance.

    I haven't been able to read my file (*.txt or *.xml). Xcode gives me the following feedback:
    Here is the script I am using. The XML parser code fragments were written by a colleague. I've confirmed this works in the Unity iPhone editor, but cannot seem to get it to read my file in Xcode/iPod.

    Code (csharp):
    1. import System.Xml;
    2. import System.IO;
    3.  
    4. static var buttonOne : boolean = false;
    5. static var buttonTwo : boolean = false;
    6. var scrollView : Vector2 = Vector2.zero;
    7. static var pageIDButton : String = "";
    8. private var docPath : String = Application.dataPath;
    9.  
    10.  
    11. function Awake ()
    12. {
    13.    
    14.     Debug.Log ("Path Before Append = " + docPath);
    15.  
    16.     if (!Application.isEditor)
    17.         docPath = docPath.Substring (0, docPath.Length - 4) + "Documents/instruction.xml";
    18.     else
    19.         docPath = docPath + "/instruction.xml";
    20.  
    21.     Debug.Log ("Path After Append = " + docPath);
    22.  
    23. }
    24.  
    25. function OnGUI ()
    26. {      
    27.  
    28.         if (GUI.Button (Rect(50, 275, 40, 40), "1"))
    29.         {
    30.             buttonOne = true;
    31.             buttonTwo = false;
    32.             Debug.Log ("Pressed 1");
    33.         }
    34.        
    35.         if (GUI.Button (Rect(390, 275, 40, 40), "2"))
    36.         {
    37.             buttonOne = false;
    38.             buttonTwo = true;
    39.             Debug.Log ("Pressed 2");
    40.         }
    41.        
    42.        
    43.         if (buttonOne)
    44.         {
    45.             pageIDButton = "1";
    46.             DisplayInstruction (pageIDButton);
    47.         }
    48.        
    49.         if (buttonTwo)
    50.         {
    51.             pageIDButton = "2";
    52.             DisplayInstruction (pageIDButton);
    53.         }
    54.  
    55. }
    56.  
    57.  
    58. function DisplayInstruction (pageIDButton : String)
    59. {
    60.    
    61.         var xDoc : XmlDocument = new XmlDocument ();
    62.         xDoc.Load (docPath);
    63.    
    64.         var xPathStatement : String = "//page[@id='" + pageIDButton + "']";
    65.         var nodeList : XmlNodeList = xDoc.SelectNodes (xPathStatement);        
    66.  
    67.         //Enumerate the NodeList
    68.         var iEnum : IEnumerator = nodeList.GetEnumerator ();      
    69.         while (iEnum.MoveNext ())
    70.         {  
    71.             var page:XmlNode = iEnum.Current;
    72.  
    73.             //Get node attribute collection and list name/value pairs
    74.             var nodeAttribs : XmlAttributeCollection = page.get_Attributes ();
    75.    
    76.         }
    77.  
    78.         var str : String = nodeAttribs["instructional_text"].Value;
    79.  
    80.         GUI.BeginGroup (Rect (Screen.width * 0.5 - 190, Screen.height * 0.5 - 100, 380, 200));
    81.             GUI.Box (Rect(0, 0, 380, 200), nodeAttribs["page_name"].Value);
    82.             scrollView = GUI.BeginScrollView (Rect (20, 20, 360, 160), scrollView, Rect (0, 0, 340, 500));
    83.             GUI.Label (Rect (0, 0, 340, 500), str);
    84.             GUI.EndScrollView ();
    85.         GUI.EndGroup ();
    86.        
    87. }
    Any suggestions and guidance greatly appreciated.
     
  9. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    if you drop it into the folder, you don't load it through external reads but through just loading the text asset.
     
  10. christopherbrown

    christopherbrown

    Joined:
    Oct 19, 2009
    Posts:
    83
    So I'm over doing it and doing it wrong up above, correct? I need to do what you and andeeee have suggested and treat it as a local text asset object?
     
  11. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    if you drop it into the assets folder then yes. the file will not be floating around as standalone file
     
  12. christopherbrown

    christopherbrown

    Joined:
    Oct 19, 2009
    Posts:
    83
    Very good. Thank you for your feedback and redirection.

    Incidentally, if you were to take the approaches above for reading an XML file, where would it reside? The iPod file system? A remote server?

    Thanks again!
     
  13. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    The above would be the application private documents folder on the iphone where you for example write your own data to you want to use later. downloaded game content / levels etc would also end there.

    all you have to do is get it from somewhere or generate the file from within the application.
     
  14. christopherbrown

    christopherbrown

    Joined:
    Oct 19, 2009
    Posts:
    83
    Thank you for clearing that up for me. :)
     
  15. Murali

    Murali

    Joined:
    Mar 3, 2010
    Posts:
    20
    This is the error i get when i create a file as

    var srs = File.CreateText(fileName);
    srs.Close();


    UnauthorizedAccessException: Access to the path "/var/mobile/Applications/D7B5FF19-7525-45C5-BAA3-9DC999195AEB/GameS.txt" is denied.
    System.IO.FileStream..ctor (System.String path, FileMode mode, FileAccess access, FileShare share)
    (wrapper remoting-invoke-with-check) System.IO.FileStream:.ctor (string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare)
    System.IO.StreamWriter..ctor (System.String path, Boolean append)
    (wrapper remoting-invoke-with-check) System.IO.StreamWriter:.ctor (string,bool)
    System.IO.File.CreateText (System.String path)
    TimeKeeper.WriteFile (System.String file)
    TimeKeeper.Start ()

    (Filename: Line: -1)


    Is there iam doing anything wrong, pls any one help me
     
  16. andeeeee

    andeeeee

    Joined:
    Jul 19, 2005
    Posts:
    8,768
    The code is valid, but the access violation means you are trying to create a file where you're not supposed to. (To be honest, I'm not sure whether/where you can create files on the iPhone.)
     
  17. Dreamora

    Dreamora

    Joined:
    Apr 5, 2008
    Posts:
    26,601
    you can create files on the iphone.
    The appropriate place though is the applications own Documents folder.
    There are 2-3 threads on the topic on the iphone dev board that should get you going (it works basically with the Application.dataPath) :)
    Alternatively the iPhone Documentations from apple contain them too.
     
  18. AnomalusUndrdog

    AnomalusUndrdog

    Joined:
    Jul 3, 2009
    Posts:
    1,551
    Found the path: http://unity3d.com/support/documentation/Manual/iphone-Downloadable-Content.html

    Code (csharp):
    1.         public static string GetiPhoneDocumentsPath () {
    2.                 // Your game has read+write access to /var/mobile/Applications/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/Documents
    3.                 // Application.dataPath returns              
    4.                 // /var/mobile/Applications/XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX/myappname.app/Data
    5.                 // Strip "/Data" from path
    6.                 string path = Application.dataPath.Substring (0, Application.dataPath.Length - 5);
    7.                 // Strip application name
    8.                 path = path.Substring(0, path.LastIndexOf('/'));  
    9.                 return path + "/Documents";
    10.         }
     
  19. s4m3

    s4m3

    Joined:
    Jan 29, 2011
    Posts:
    4
    Hey there,

    so I used TouchSoft's code to write and read data of my app to the filesystem. This works fine with UnityRemote and my app running on the editor. I am currently developing an IPhone game and I want to get some HCI info about that game, which i am storing now in Assets. Since I will be running some testing with different people on the IPhone itself, i would need to get the information stored on the IPhone back on my Mac. But how do I access the text. Of course I could display it on the IPhone but since it is going to be a lot of info, i do not want to read and write it by hand but copy the file instead.
    So is there a possibility to just access the filesystem of my IPod? Do I have to implement some sort of network to send the data back on a server? Via E-Mail maybe? This all would be a lot of work, since i would only need networking for this purpose.

    EDIT: There is IPhone Explorer. Easy enough. Wrong thread for my question anyways...
     
    Last edited: Feb 8, 2011