Advanced   Java   Services DriveInfo, DirectoryInfo, FileInfo

Übersicht über die Klassen und Enums

Die folgende Graphik zeigt die Hierarchie der Klassen Directory-, File-, und FilesystemInfo. Bei Klassen wurde der name "class" weggelassen. Bei Klassen und Enums aus dem Assembly "System.IO" wird dieses Assembly nicht explizit angegeben. Auf die Enums wird nicht näher eingegangen.


DriveInfo

Mit DriveInfo kann man sich Informationen über bestimmte Laufwerke holen, so kann man etwa das Dateiformat ermitteln oder die Speichergröße. Auch gibt es eine statische Methode, die einem ein Array aller Laufwerke liefert, genauer gesagt erhält man ein Array vom Typ DriveInfo.

Konstruktor
DriveInfo(string driveName) Provides access to information on the specified drive.
Wichtigste Methode
Returntyp Name der Methode
public static DriveInfo[] GetDrives()
Retrieves the drive names of all logical drives on a computer.
Exceptions: IOException (An I/O error occurred (for example, a disk error or a drive was not ready).), UnauthorizedAccessException (The caller does not have the required permission.)
Properties
Name Description
AvailableFreeSpace Indicates the amount of available free space on a drive.
Exceptions: IOException (An I/O error occurred (for example, a disk error or a drive was not ready).)
DriveFormat Gets the name of the file system, such as NTFS or FAT32.
Exceptions: IOException (An I/O error occurred (for example, a disk error or a drive was not ready).)
DriveType Gets the drive type.
Exceptions: IOException (An I/O error occurred (for example, a disk error or a drive was not ready).)
IsReady Gets a value indicating whether a drive is ready.
Exceptions: IOException (An I/O error occurred (for example, a disk error or a drive was not ready).)
Name Gets the name of a drive.
Exceptions: IOException (An I/O error occurred (for example, a disk error or a drive was not ready).)
RootDirectory Gets the root directory of a drive.
Exceptions: IOException (An I/O error occurred (for example, a disk error or a drive was not ready).)
TotalFreeSpace Gets the total amount of free space available on a drive.
Exceptions: IOException (An I/O error occurred (for example, a disk error or a drive was not ready).)
TotalSize Gets the total size of storage space on a drive.
Exceptions: IOException (An I/O error occurred (for example, a disk error or a drive was not ready).)
VolumeLabel Gets or sets the volume label of a drive.
Exceptions: IOException (An I/O error occurred (for example, a disk error or a drive was not ready).) SecurityException (The caller does not have the required permission.), UnauthorizedAccessException (The volume label is being set on a network or CD-ROM drive.)


Codebeispiel
using System.IO;  // man braucht kein assembly hinzufügen

static void Main(string[] args)
{
   try
   {
      DriveInfo[] drives = DriveInfo.GetDrives();

      foreach (DriveInfo di in drives)
      {
         Console.WriteLine("Name: {0}  Type: {1}", di.Name, di.DriveType);
         Console.WriteLine("VolumeLabel: {0}", di.VolumeLabel);
         Console.WriteLine("TotalSize: {0}", di.TotalSize);
         Console.WriteLine("TotalFreeSpace: {0}", di.TotalFreeSpace);
         Console.WriteLine("AvailableFreeSpace: {0}", di.AvailableFreeSpace);
         Console.WriteLine("Dateiystem: {0}", di.DriveFormat);
         Console.WriteLine("------------------------------\n");
      }
   }
   catch (SystemException ex)
   {
      Console.WriteLine("{0}", ex.Message);
   }

}

GetDrives() ist bereits innerhalb von try, weil es IOException oder UnauthorizedAccessException werfen kann. VolumeLabel kann zusätzlich noch SecurityException werfen. SystemException im catch-Zweig ist die erste gemeinsame Oberklasse aller möglichen Exceptions.


DirectoryInfo

Ein Objekt vomm Typ DirectoryInfo liefert Informationen über ein Verzeichnis. es gibt auch Methoden, die sämtliche Unterverzeichnisse oder alle Dateien in einem Verzeichnis liefern. Die Exceptions werden nur beim Konstruktor angegeben.

Konstruktor
public DirectoryInfo(string path) Initializes a new instance of the DirectoryInfo class on the specified path.
Exceptions: ArgumentException (path contains invalid characters such as ", <, >.) ArgumentNullException (Path is null.) PathTooLongException (The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. The specified path, file name, or both are too long.) SecurityException (The caller does not have the required permission.)
Einige Methoden
Returntyp Name der Methode
public void Create()
Creates a directory.
public DirectoryInfo CreateSubdirectory(string path)
Creates a subdirectory or subdirectories on the specified path. The specified path can be relative to this instance of the DirectoryInfo class.
public override void Delete()
Deletes this DirectoryInfo if it is empty.
public void Delete(bool recursive)
Deletes this instance of a DirectoryInfo, specifying whether to delete subdirectories and files.
public DirectoryInfo[] GetDirectories()
Returns the subdirectories of the current directory.
public DirectoryInfo[] GetDirectories(string searchPattern)
Returns an array of directories in the current DirectoryInfo matching the given search criteria.
public FileInfo[] GetFiles()
Returns a file list from the current directory.
public FileInfo[] GetFiles(string searchPattern)
Returns a file list from the current directory matching the given searchPattern.
public FileSystemInfo[] GetFileSystemInfos()
Returns an array of strongly typed FileSystemInfo entries representing all the files and subdirectories in a directory.
public FileSystemInfo[] GetFileSystemInfos(string searchPattern)
Retrieves an array of strongly typed FileSystemInfo objects representing the files and subdirectories matching the specified search criteria.
Fields
Typ Name
string FullPath
Represents the fully qualified path of the directory or file. (Inherited from FileSystemInfo.)
string OriginalPath
The path originally specified by the user, whether relative or absolute. (Inherited from FileSystemInfo.)
Einige Properties
Typ Name
FileAttributes Attributes
Gets or sets the FileAttributes of the current FileSystemInfo. (Inherited from FileSystemInfo.)
override bool Exists
Gets a value indicating whether a file exists. [Overrides FileSystemInfo::Exists]
string Extension
Gets the string representing the extension part of the file. [Inherited from FileSystemInfo]
string FullName
Gets the full path of the directory or file. [Inherited from FileSystemInfo]
override string Name
Gets the name of the file. [Overrides FileSystemInfo::Name]
DirectoryInfo Parent
Gets the parent directory of a specified subdirectory.
DirectoryInfo Root
Gets the root portion of a path.


Codebeispiel
using System;
using System.IO;  // man braucht kein assembly hinzufügen

class Program
{
   static void Main(string[] args)
   {
      try
      {
         DirectoryInfo dirInfo = new DirectoryInfo("d:\\csharp");
         DirectoryInfo[] direcs = dirInfo.GetDirectories();

         Console.WriteLine("alle verzeichnisse in d:\\csharp:");
         Console.WriteLine("------------------------------");
         foreach (DirectoryInfo di in direcs)
         {
            Console.WriteLine("{0}", di.Name);
         }
      }
      catch(SystemException ex)
      {
         Console.WriteLine("{0}", ex.Message);
      }
   }
}

FileInfo

Konstruktor
public FileInfo(string fileName) Initializes a new instance of the FileInfo class, which acts as a wrapper for a file path.
Exceptions: ArgumentException (path contains invalid characters such as ", <, >.) ArgumentNullException (Path is null.) PathTooLongException (The specified path, file name, or both exceed the system-defined maximum length. For example, on Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260 characters. The specified path, file name, or both are too long.) NotSupportedException (fileName contains a colon (:) in the middle of the string.) SecurityException (The caller does not have the required permission.) UnauthorizedAccessException (Access to fileName is denied.)
Einige Methoden
Returntyp Name der Methode
StreamWriter AppendText()
Creates a StreamWriter that appends text to the file represented by this instance of the FileInfo.
FileInfo CopyTo(string destFileName, bool overwrite)
Copies an existing file to a new file, allowing or disallowing the overwriting of an existing file.
FileStream Create()
Creates a FileStream.
StreamWriter CreateText()
Creates a StreamWriter that writes a new text file.
override void Delete()
Permanently deletes a file. [Overrides FileSystemInfo::Delete()]
void MoveTo(string destFileName)
Moves a specified file to a new location, providing the option to specify a new file name.
FileStream Open(FileMode mode)
Opens a file in the specified mode.
FileStream Open(FileMode mode, FileAccess access)
Opens a file in the specified mode with read, write, or read/write access.
FileStream OpenRead()
Creates a read-only FileStream.
StreamReader OpenText()
Creates a StreamReader with UTF8 encoding that reads from an existing text file.
FileStream OpenWrite()
Creates a write-only FileStream.
FileInfo Replace()
Replaces the contents of a specified file with the file described by the current FileInfo object, deleting the original file, and creating a backup of the replaced file.
Fields
Typ Name
string FullPath
Represents the fully qualified path of the directory or file. (Inherited from FileSystemInfo.)
string OriginalPath
The path originally specified by the user, whether relative or absolute. (Inherited from FileSystemInfo.)
Einige Properties
Typ Name
FileAttributes Attributes
Gets or sets the FileAttributes of the current FileSystemInfo. (Inherited from FileSystemInfo.)
DirectoryInfo Directory
Gets an instance of the parent directory.
string DirectoryName
Gets a string representing the directory's full path.
override bool Exists
Gets a value indicating whether a file exists. [Overrides FileSystemInfo::Exists]
string Extension
Gets the string representing the extension part of the file. [Inherited from FileSystemInfo]
string FullName
Gets the full path of the directory or file. [Inherited from FileSystemInfo]
long Length
Gets the size, in bytes, of the current file.
override string Name
Gets the name of the file. [Overrides FileSystemInfo::Name]


Codebeispiel
using System;
using System.IO;  // man braucht kein assembly hinzufügen

class Program
{
   static void Main(string[] args)
   {
      try
      {
         DirectoryInfo dirInfo = new DirectoryInfo("d:\\csharp");

         FileInfo[] files = dirInfo.GetFiles();
         // gibt nicht null, sondern ein array der länge 0 zurück
         Console.WriteLine("------------------------------");
         Console.WriteLine("alle dateien in d:\\csharp:");
         Console.WriteLine("------------------------------");
         if (files.Length == 0)
         {
            Console.WriteLine("Das verzechinis enthaelt keine Dateien\n");
         }
         else
         {
            foreach (FileInfo fi in files)
            {
               Console.WriteLine("{0}", fi.Name);
            }
         }
      }
      catch(SystemException ex)
      {
         Console.WriteLine("{0}", ex.Message);
      }
   }
}