- Home /
 
 
               Question by 
               JoshMBeyer · Dec 09, 2014 at 06:07 PM · 
                c#fileaccess.txt  
              
 
              Retrieve and assign data from a .txt file?
I have a text file with 1000 lines of text. I want each line to be a value named one - onethousand. I want to access this file, and get all the text. And be able to access each line as a string variable. How would I do this in the most simple way? and should I use and array or List to beable to randomly access 4 at a time?
               Comment
              
 
               
              Answer by XerocakeGAME · Dec 09, 2014 at 08:43 PM
If I understand your question properly, you should be able to use System.IO for reading and writing to files. Below is an example on how to read and write the values the file and store the values in a List.
 //READING A FILE
 
 
     public List<string> texttoread = new List<string>(); //Where the values from the text file will be stored
 
     public void Read()
     {
         string curline; //current line
         System.IO.StreamReader file = new System.IO.StreamReader(PATH TO FILE);
         while((curline = file.ReadLine()) != null)
         {
             texttoread.Add(curline);
         }
     }
 
         
         //SAVING TO FILE
         public List<string> texttowrite = new List<string>(); //The values that will be saved into the file
     
         public void Write()
     {
         System.IO.StreamWriter file2 = new System.IO.StreamWriter(PATH_TO_WRITE);
         foreach(string i in texttowrite)
         {
             file2.Write(i.ToString());
         }
         file2.Close();
     }
 
 
              Your answer