본문 바로가기

Software/C#.Net

File Type

// Obtain FileStream object via File.Create().

using(FileStream fs = File.Create(@"C:\Test.dat"))

{

}

// Obtain FileStream object via File.Open().

using(FileStream fs2 = File.Open(@"C:\Test2.dat",

FileMode.OpenOrCreate,

FileAccess.ReadWrite, FileShare.None))

{

}

// Get a FileStream object with read-only permissions.

using(FileStream readOnlyStream = File.OpenRead(@"Test3.dat"))

{

}

// Get a FileStream object with write-only permissions.

using(FileStream writeOnlyStream = File.OpenWrite(@"Test4.dat"))

{

}

// Get a StreamReader object.

using(StreamReader sreader = File.OpenText(@"C:\boot.ini"))

{

}

// Get some StreamWriters.

using(StreamWriter swriter = File.CreateText(@"C:\Test3.txt"))

{

}

using(StreamWriter swriterAppend = File.AppendText(@"C:\FinalTest.txt"))

{

}


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

위의 함수들로 데이터들을 배치로 몇줄 만으로 바로 Read/Write 할수있다.

여기 예제를 보자.

using System;

using System.IO;

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();

   }

}