Inhaltsverzeichnis

Manipulieren von Dateien und Verzeichnissen in C#

1- Class hierarchy

Class Description
File File is a utility class. It provides static methods for the creation, copying, deletion, moving, and opening of a single file, and aids in the creation of FileStream objects.
Directory Directory is a utility class, It provides static methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited.
FileInfo FileInfo is a class that represents a file. It provides properties and instance methods for the creation, copying, deletion, moving, and opening of files, and aids in the creation of FileStream objects. This class cannot be inherited.
DirectoryInfo DirectoryInfo is a class representing a directory. It provides methods for creating, moving, and enumerating through directories and subdirectories. This class cannot be inherited.
DriveInfo DirveInfo is a class, it provides access to information on a drive.

2- File

File ist eine Utility-Klasse. Sie bietet die static MEthode zur Erstellung, Kopie, Lösch, Bewegung und Öffnung einer File. und unterstützt bei der Erstellung des Objekt  FileStream.
Das folgende Beispiel prüft, ob der Pfad der File existiert oder nicht. Wenn ja, lösch die File
DeleteFileDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileDirectoryTutorial
{
    class DeleteFileDemo
    {
        public static void Main(string[] args)
        {
            string filePath = "C:/test/test.txt";

            // Check if the file exists or not
            if (File.Exists(filePath))
            {
                // Delete file
                File.Delete(filePath);

                // Check again
                if (!File.Exists(filePath))
                {
                    Console.WriteLine("File deleted...");
                }

            }
            else
            {
                Console.WriteLine("File test.txt does not yet exist!");
            }

            Console.ReadKey();
        }
    }

}
Das Beispiel durchführen
Die Änderung des Filenamen kann die Bewegung der File zum anderen Ordner und die Änderung des Filename einschließen. Falls die File in anderen Ordner bewegt wird, stellen Sie sicher, dass der neue Ordner existiert.
RenameFileDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileDirectoryTutorial
{
    class RenameFileDemo
    {
        public static void Main(string[] args)
        {
            String filePath = "C:/test/test.txt";

            if (File.Exists(filePath))
            {
                Console.WriteLine(filePath + " exist");

                
                Console.WriteLine("Please enter a new name for this file:");
                
                // String that user enters.
                // Example: C:/test/test2.txt
                string newFilename = Console.ReadLine();

                if (newFilename != String.Empty)
                {
                    // Rename the file may include moving the file to another folder and renaming the file.
                    // You must ensure that the destination folder exists.
                    // (Else, DirectoryNotFoundException will be thrown). 
                    File.Move(filePath, newFilename);

                    if (File.Exists(newFilename))
                    {
                        Console.WriteLine("The file was renamed to " + newFilename);
                    }
                }
            }
            else
            {
                Console.WriteLine("Path " + filePath + " does not exist.");
            }

            Console.ReadLine();
        }
    }

}
Running the example:

3- Directory

Directory ist eine Utility Klasse. Er bietet die static Methode um die Ordner und die untergeordneten Ordner zu erstellen, bewegen und listieren. Die Klass darf keine untergeordneten Klassen haben
Zum Beispiel: Überprüfen, ob der Pfad des Ordner existiert oder nicht. Wenn nicht, die Information der Erstellungszeitpunkt, des letzten Eingabe in der Ordner aufschreiben
DirectoryInformationDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileDirectoryTutorial
{
    class DirectoryInformationDemo
    {
        public static void Main(string[] args)
        {
            String dirPath = "C:/test/CSharp";

            // Check if a directory path exists or not.
            bool  exist = Directory.Exists(dirPath);

            // If not exist, create it
            if (!exist)
            {
                Console.WriteLine(dirPath + " does not exist.");
                Console.WriteLine("Create directory: " + dirPath);

                // Create Directory
                Directory.CreateDirectory(dirPath);
            }

            Console.WriteLine("Directory Information " + dirPath);

            // Print out infos

            // Creation time
            Console.WriteLine("Creation time: "+ Directory.GetCreationTime(dirPath));

            // Last Write time.
            Console.WriteLine("Last Write Time: " + Directory.GetLastWriteTime(dirPath));

            // Parent directory
            DirectoryInfo parentInfo = Directory.GetParent(dirPath);

            Console.WriteLine("Parent directory: " + parentInfo.FullName);


            Console.Read();
        }
    }
     
}
Running the example:
Den Name des Ordner ändern
Sie können den Name des Ordner ändern. Das kann diesen Ordner aus der Vaterordner verlassen. Aber Sie müssen guarantieren, dass der neue Ordner schon existiert. Das folgende Beispiel bezeichnet die Änderung eines Ordnername
RenameDirectoryDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileDirectoryTutorial
{
    class RenameDirectoryDemo
    {
        public static void Main(string[] args)
        {
            // A directory path.
            String dirPath = "C:/test/CSharp";

            // If this path exists.
            if (!Directory.Exists(dirPath))
            {
                Console.WriteLine(dirPath + " does not exist.");
                Console.Read();

                // End method.
                return;
            }

            Console.WriteLine(dirPath + " exist");


            Console.WriteLine("Please enter a new name for this directory:");

            // String that the user enters.
            // example: C:/test2/Java
            string newDirname = Console.ReadLine();

            if (newDirname == String.Empty)
            {
                Console.WriteLine("You not enter new directory name. Cancel rename.");
                Console.Read();

                // End
                return;
            }

            // If the user enters a new directory path already exists.
            if (Directory.Exists(newDirname))
            {
                Console.WriteLine("Cannot rename directory. New directory already exist.");
                Console.Read();

                // End
                return;
            }

            // Parent directory.
            DirectoryInfo parentInfo = Directory.GetParent(newDirname);

            // Create parent folder of the new folder that the user enters.
            Directory.CreateDirectory(parentInfo.FullName);

            // You can change folder name.
            // It can make that folder to move from existing parent directory.
            // But you must ensure that the new parent directory have been already existed
            // (Else, DirectoryNotFoundException will be thrown)
            Directory.Move(dirPath, newDirname);

            if (Directory.Exists(newDirname))
            {
                Console.WriteLine("The directory was renamed to " + newDirname);
            }


            Console.ReadLine();
        }
    }

}
Running the example:
Das folgende Beispeil druckt alle Nachkommenordner (Kind, Enkel,...) eines Ordner aus
EnumeratingDirectoryDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileDirectoryTutorial
{
    class EnumeratingDirectoryDemo
    {
        public static void Main(string[] args)
        {
            string dirPath = "C:/Windows/System32";

            PrintDirectory(dirPath);

            Console.Read();
        }

        // Recursive method to list the subfolders of a folder.
        public static void PrintDirectory(string dirPath)
        {
            try
            {
                // You do not have sufficient  access to the folder 'dirPath',
                // UnauthorizedAccessException exception will be thrown.
                IEnumerable<string> enums = Directory.EnumerateDirectories(dirPath);

             
                List<string> dirs = new List<string>(enums);

                foreach (var dir in dirs)
                {
                    Console.WriteLine(dir);

                    // Recursive to search subdirectories.
                    PrintDirectory(dir);
                }
            }
            // Security error.
            catch (UnauthorizedAccessException e)
            {
                Console.WriteLine("Can not access directory: " + dirPath);
                Console.WriteLine(e.Message);
            }
        }
    }

}
Running the example:

4- FileInfo

FileInfo ist eine Klasse zur Vertretung einer File. Er bietet die Attribute, die Methode um die FIle zu erstellen, kopieren, löschen, bewegen und öffnen. Er unterstützt bei der Erstellung des Objekt. Diese Klasse darf keine untergeordnete Klasse haben
Der Unterschied zwischen 2 Klasse  File und  FileInfo liegt, dass File ist eine Utility-Klasse, seine allen Methode sind static , Und  FileInfo vertretet eine bestimmten FIle
FileInfoDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
 
namespace FileDirectoryTutorial
{
    class FileInfoDemo
    {
        static void Main(string[] args)
        {
            // An object that represents a file.
            FileInfo testFile = new FileInfo("C:/test/test.txt");

 

            if (testFile.Exists)
            {
                Console.WriteLine(testFile.FullName + " exist.");

                // Creation time
                Console.WriteLine("Creation time: " + testFile.CreationTime);

                // Last Write Time
                Console.WriteLine("Last Write Time " + testFile.LastWriteTime);

                // Directory containing
                Console.WriteLine("Directory Name: " + testFile.DirectoryName);
            }
            else
            {
                Console.WriteLine(testFile.FullName + " does not exist.");
            }
            Console.Read();
        }
    }

}
Running the example:
Die Änderung des Filename kann die Filebewegung zum anderen Ordner und die Änderung des Filename einschließen. Falls die FIle zum anderen Ordner bewegt wird, guarantieren Sie,dass der neue Ordner schon existiert.
RenameFileInfoDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileDirectoryTutorial
{
    class RenameFileInfoDemo
    {
        public static void Main(string[] args)
        {

            FileInfo fileInfo = new FileInfo("C:/test/test.txt");

            if (!fileInfo.Exists)
            {
                Console.WriteLine(fileInfo.FullName + " does not exist.");
                Console.Read();            
                return;
            }


            Console.WriteLine(fileInfo.FullName + " exist");


            Console.WriteLine("Please enter a new name for this file:");

            // String that user enters
            // example: C:/test/test2.txt
            string newFilename = Console.ReadLine();

            if (newFilename == String.Empty)
            {
                Console.WriteLine("You not enter new file name. Cancel rename");

                Console.Read();

                // End method
                return;
            }

            FileInfo newFileInfo = new FileInfo(newFilename);

            // If newFileInfo exist (Can not rename).
            if (newFileInfo.Exists)
            {
                Console.WriteLine("Can not rename file to " + newFileInfo.FullName + ". File already exist.");

                Console.Read();

                // End method
                return;
            }

            // Create parent directory of newFileInfo
            newFileInfo.Directory.Create();

            // Rename
            fileInfo.MoveTo(newFileInfo.FullName);

            // refresh.
            newFileInfo.Refresh();

            if (newFileInfo.Exists)  
            {
                Console.WriteLine("The file was renamed to " + newFileInfo.FullName);
            }

            Console.ReadLine();
        }
    }

}
Running the example:

5- DirectoryInfo

DirectoryInfo ist eine Klasse zur Vertretung eines Ordner. Er bietet die Methode um die Ordner und die untergeordneten Ordner zu erstellen, bewegen, listieren. Diese Klass darf keine untergeordneten Klasse haben.
Der Unterschied zwischen die Klasse  Directory und  DirectoryInfo liegt, dass Directory ist eine Utility-Klasse, alle MEthode sind static. Und DirectoryInfo vertretet einen bestimmten Ordner
DirectoryInfoDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileDirectoryTutorial
{
    class DirectoryInfoDemo
    {
        static void Main(string[] args)
        {
            // An object representing a folder.
            DirectoryInfo dirInfo = new DirectoryInfo("C:/Windows/System32/drivers");

            // Write out creation time.
            Console.WriteLine("Creation time: " + dirInfo.CreationTime);

            // Last write time
            Console.WriteLine("Last Write Time " + dirInfo.LastWriteTime);

            // Full name
            Console.WriteLine("Directory Name: " + dirInfo.FullName);

            // Array of subfolders.
            DirectoryInfo[] childDirs = dirInfo.GetDirectories();

            // An array of files in the folder
            FileInfo[] childFiles = dirInfo.GetFiles();

            foreach(DirectoryInfo childDir in childDirs ){
                Console.WriteLine(" - Directory: " + childDir.FullName);
            }

            foreach (FileInfo childFile in childFiles)
            {
                Console.WriteLine(" - File: " + childFile.FullName);
            }


            Console.Read();
        }
    }

}
Running the example:

6- DriveInfo

DirveInfo ist eine Klasse, er bietet die Methode zum Zugang der Festplatte
DriveInfoDemo.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace FileDirectoryTutorial
{
    class DriveInfoDemo
    {
        static void Main(string[] args)
        {
            DriveInfo[] drives = DriveInfo.GetDrives();

            foreach (DriveInfo drive in drives)
            {
                Console.WriteLine(" ============================== ");

                // Name of Drive
                Console.WriteLine("Drive {0}", drive.Name);

                // Drive type (Removable,..)
                Console.WriteLine("  Drive type: {0}", drive.DriveType);

                // If drive is ready.
                if (drive.IsReady)
                {
                    Console.WriteLine("  Volume label: {0}", drive.VolumeLabel);
                    Console.WriteLine("  File system: {0}", drive.DriveFormat);
                    Console.WriteLine(
                        "  Available space to current user:{0, 15} bytes",
                        drive.AvailableFreeSpace);

                    Console.WriteLine(
                        "  Total available space:          {0, 15} bytes",
                        drive.TotalFreeSpace);

                    Console.WriteLine(
                        "  Total size of drive:            {0, 15} bytes ",
                        drive.TotalSize);
                }
            }

            Console.Read();
        }
    }

}
Running the example: