Advanced   Java   Services File Back Next Up Home


File

Die Klasse File im Namespace System.IO ist eine typische Utilityklasse und stellt eine ganze Reihe von äußerst nützlichen Methoden für den schreibenden und lesenden Zugriff auf Dateien zur Verfügung. Da alle diese Methoden statisch sind wurde sie als statische Klasse angelegt. Sie leitet sich also direkt von Object ab und kann keine Kindklassen besitzen. File implementiert auch das Interface IDisposable nicht. So kann man die using-Klausel höchstens dort einsetzen, wo ein Reader oder ein Writer oder ein Stream zurückgegeben werden.

Einige Methoden
Returntyp Name der Methode
void AppendAllText()
Overloaded. Appends the specified stringto the file, creating the file if it does not already exist.
StreamWriter AppendText(string path)
Creates a StreamWriter that appends UTF-8 encoded text to an existing file.
void Copy(string sourceFile, string destFile)
Overloaded. Copies an existing file to a new file.
FileStream Create(string path)
Overloaded. Creates a file in the specified path.
StreamWriter CreateText(string path)
Creates or opens a file for writing UTF-8 encoded text.
void Delete(string path)
Deletes the specified file. An exception is not thrown if the specified file does not exist.
bool Exists(string path)
Determines whether the specified file exists.
void Move(string sourceFile,string destFile)
Moves a specified file to a new location, providing the option to specify a new file name.
FileStream Open(string path, FileMode mode)
Overloaded. Opens a FileStream on the specified path.
FileStream OpenRead(string path)
Opens an existing file for reading.
StreamReader OpenText(string path)
Opens an existing UTF-8 encoded text file for reading.
FileStream OpenWrite(string path)
Opens an existing file for writing.
byte[] ReadAllBytes(FileStream)
Opens a binary file, reads the contents of the file into a byte array, and then closes the file.
string[] ReadAllLines(string path, Encoding enc)
Overloaded. Opens a text file, reads all lines of the file into a string array, and then closes the file.
string ReadAllText(string path, Encoding enc)
Overloaded. Opens a text file, reads all lines of the file into a string, and then closes the file.
void Replace(string sourceFile, string destFile, string backupFile)
Overloaded. Replaces the contents of a specified file with the contents of another file, deleting the original file, and creating a backup of the replaced file.
void WriteAllBytes(string path, byte[] bytes)
Creates a new file, writes the specified byte array to the file, and then closes the file. If the target file already exists, it is overwritten.
void WriteAllLines(string path, string[] contents, Encoding encoding)
Overloaded. Creates a new file, writes the specified string to the file, and then closes the file. If the target file already exists, it is overwritten.
void WriteAllText(string path, string text, Encoding enc)
Overloaded. Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.

Exceptions

Für jede Methode gibt es ein ganzes Bündel von Exceptions, die berücksichtigt werden wollen. Hier eine Übersicht. Für die Einzelheiten konsultiere man die API.


Codebeipiel 1

Die "All"-Methoden sind für kleine Dateien äußerst komfortabel.

static void Main(string[] args)
{
   try
   {
      string text = File.ReadAllText("foo.txt", Encoding.GetEncoding(1252)); // Windows-1252
      // edit text
      File.WriteAllText("foofoo", text, Encoding.UTF8);
   }
   catch (Exception ex)
   {
      //ArgumentException
      //ArgumentNullException
      //FileNotFoundException
      //IOException
      //NotSupportedException
      //PathTooLongException
      //PathTooLongException
      //SecurityException
      //UnauthorizedAccessException
   }
}

Codebeipiel 2

Will man die Exceptions von OpenText() abfangen, braucht man try-catch über using. Will man die Exceptions von Readline() sofort abfangen, braucht man try-catch innerhalb von using.

static void Main(string[] args)
{
   StreamReader reader = null;
   List<string> lines = null;

   try
   {
      using (reader = File.OpenText("../../foo.txt"))
      {
         lines = new List<string>();
         try
         {
            string line = null;
            while ((line = reader.ReadLine()) != null)
            {
               // edit line
               lines.Add(line.Trim());
            }
         }
         catch (Exception ex)
         {
            // Readline:
            //OutOfMemoryException
            //IOException
         }
      }

      string[] zeilen = lines.ToArray(); // System.InvalidCastException
      File.WriteAllLines("../../foofoo.txt", zeilen);
   }
   catch (Exception ex)
   {
      //ArgumentException
      //ArgumentNullException
      //DirectoryNotFoundException
      //FileNotFoundException
      //NotSupportedException
      //PathTooLongException
      //UnauthorizedAccessException
   }
}
Valid XHTML 1.0 Strict top Back Next Up Home