Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by ragnaros100 · Jul 07, 2012 at 10:34 AM · c#saveloadreadexplanation

Code explanation - C#

continuation of this

Hi. In my last question (link) I was provided a piece of code that can read text documents. It is excactly what I need for my project, but the comments on the code wasnt really that descriptive (no offense @Drakestar). So I was wondering if there was anyone that would help me out and explain me what variables I need to edit to read the (example:) 4th line of a file located at "C:/MyGame/data/document.txt"

-thanks :)

EDIT: here's the code:

 using System.Text;
 using System.IO;  
 
 private bool Load(string fileName)
 {
     // Handle any problems that might arise when reading the text
     try
     {
         string line;
         // Create a new StreamReader, tell it which file to read and what encoding the file
         // was saved as
         StreamReader theReader = new StreamReader(fileName, Encoding.Default);
 
         // Immediately clean up the reader after this block of code is done.
         // You generally use the "using" statement for potentially memory-intensive objects
         // instead of relying on garbage collection.
         // (Do not confuse this with the using directive for namespace at the 
         // beginning of a class!)
         using (theReader)
         {
             // While there's lines left in the text file, do this:
             do
             {
                 line = theReader.ReadLine();
 
                 if (line != null)
                 {
                     // Do whatever you need to do with the text line, it's a string now
                     // In this example, I split it into arguments based on comma
                     // deliniators, then send that array to DoStuff()
                     string[] entries = line.Split(',');
                     if (entries.Length > 0)
                         DoStuff(entries);
                 }
             }
             while (line != null);
 
             // Done reading, close the reader and return true to broadcast success    
             theReader.Close();
             return true;
             }
         }
 
         // If anything broke in the try block, we throw an exception with information
         // on what didn't work
         catch (Exception e)
         {
             Console.WriteLine("{0}\n", e.Message);
             return false;
         }
     }
 }


Comment
Add comment · Show 2
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image whydoidoit · Jul 07, 2012 at 10:36 AM 1
Share

So what you have there is basically something that will process the file line by line - DoStuff will be called for each line of the file. If you want effectively random access you should do something slightly different.

avatar image ragnaros100 · Jul 07, 2012 at 10:50 AM 0
Share

thanks, but I actually asked for where to edit my file path into and how I could assign the read line to a varible (an interger or string)

1 Reply

· Add your reply
  • Sort: 
avatar image
4
Best Answer

Answer by whydoidoit · Jul 07, 2012 at 10:39 AM

You could read the whole file into a list and then you could access any line you like:

   import System.Collections.Generic;
  import System.Linq;
   import System.IO;

   var fileLines : List.<String>;

   function ReadFile() {
      var sr = File.OpenText("whatever.txt");
      fileLines = sr.ReadToEnd().Split("\n"[0]).ToList();
      sr.Close();
   }

Now you have a list of lines that you can insert into, get a specific line from - whatever. If you want to write them back out you can just do:

  var wholeFileText = String.Join("\n", fileLines.ToArray());

To get line 4 you just do fileLines[3].

Comment
Add comment · Show 9 · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image ragnaros100 · Jul 07, 2012 at 10:51 AM 0
Share

I dont mean to be rude. But please write in C# :) I dont know javascript that well yet...

avatar image whydoidoit · Jul 07, 2012 at 11:11 AM 1
Share

Sure

  using System.Collections.Generic;
  using System.Linq;
  using System.IO;

  public List<String> fileLines;
  
  public void ReadFile(string filename)
  {
       var sr = File.OpenText(filename);
       fileLines = sr.ReadToEnd().Split('\n').ToList();
       sr.Close();
  }

If you are using a CSV file however:

  using System.Collections.Generic;
  using System.Linq;
  using System.IO;

  public List<List<String>> filedata;
  
  public void ReadFile(string filename)
  {
       var sr = File.OpenText(filename);
       filedata = sr.ReadToEnd().Split('\n').Select(s=>s.Split(',').ToList()).ToList();
       sr.Close();
  }

This will give you the ability to access the data by row and column:

   var myData = filedata[4][3]; // Row 5 column 4
avatar image ragnaros100 · Jul 07, 2012 at 11:14 AM 0
Share

thanks :) thats all good. But where do I put the "C:/$$anonymous$$yGame/data/document.txt" ?

avatar image whydoidoit · Jul 07, 2012 at 11:23 AM 1
Share

You pass it as the filename:

    void Start() 
    {
            ReadFile(yourFileNameHere);
    }

Bear in $$anonymous$$d that your file won't be there during a build. You should ins$$anonymous$$d do this differently as a text Resource Asset.

avatar image ragnaros100 · Jul 07, 2012 at 11:29 AM 0
Share

I already have a script that creates a text file :) Thanks :)

Show more comments

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

7 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Distribute terrain in zones 3 Answers

Multiple Cars not working 1 Answer

Regarding reset the state to the first time we start to play 0 Answers

Error: CS0200 | Read only array? 1 Answer

Should I use c# or Unityscript? 1 Answer


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges