Showing posts with label files. Show all posts
Showing posts with label files. Show all posts

Saturday, 23 June 2012

How to Read And Write List to file

c#, load List from file uses the StreamReader ReadLine 


List<string> dataFile = new List<string>();          
using (StreamReader r = new StreamReader(edSourceFileToReplaceStrings.Text))
while ((lineData = r.ReadLine()) != null)
    dataFile.Add(lineData);


c#, save List<String> to file uses the StreamWriter WriteLine

using (System.IO.StreamWriter file = new System.IO.StreamWriter(@oDialog.FileName))
foreach (string line in dataFile)
    file.WriteLine(line);

Thursday, 23 June 2011

how to handle files, directories and drives

problem

c# - how to handle files, directories and drives --- Working with the File Type --- in practice! >>guide<<
difficulty level

3/10 :|
compatibility

flex 4.0
solution

Method Meaning in Life
ReadAllBytes() Opens the specified file, returns the binary data as an array of bytes, and then closes the file
ReadAllLines() Opens a specified file, returns the character data as an array of strings, and then closes the file
ReadAllText() Opens a specified file, returns the character data as a System.String, and then closes the file
WriteAllBytes() Opens the specified file, writes out the byte array, and then closes the file
WriteAllLines() Opens a specified file, writes out an array of strings, and then closes the file
WriteAllText() Opens a specified file, writes the character data, and then closes the file
Using these new methods of the File type, you are able to read and write batches of data in just a few lines of code. Even better, each of these new members automatically closes down the underlying file handle. For example, the following console program (named SimpleFileIO) will persist the string data into a new file on the C drive (and read it into memory) with minimal fuss:

using System;
using System.IO;   // important!
class Program
{
  static void Main(string[] args)
  {
    Console.WriteLine("***** Simple IO with the File Type *****\n");
    string[] myTasks = {
    "Fix bathroom sink", "Call Dave",
    "Call Mom and Dad", "Play Xbox 360"};
    // Write out all data to file on C drive.
    File.WriteAllLines(@"C:\tasks.txt", myTasks);
    // Read it all back and print out.
    foreach (string task in File.ReadAllLines(@"C:\tasks.txt"))
      Console.WriteLine("TODO: {0}", task);
    Console.ReadLine();
  }
}