WPF: Prüfen und Erstellen von Ordnern
Aufgabe:
Wie prüft man mit WPF,C# ob ein Verzeichnis existiert und wie erstellt man neue Verzeichnisse.
Lösung:
Man prüft auf Verzeichnisse direkt mit
Directory.Exists(Pfad)
Und erstellt neue Ordner mit
Directory.CreateDirectory(Neuer_Pfad)
Code Beispiel in C#, WPF
//--< check and create Directory >--
//*if subfolder does not exist then create one
String sPath_SubDirectory = folder.FullName + "\\" + sDate;
if (Directory.Exists(sPath_SubDirectory)==false )
{
Directory.CreateDirectory(sPath_SubDirectory);
}
//--</ check and create Directory >--
|
Für die Verwendung von Directory und DirectoryInfo benötigt man den Namespace System.IO
//--< using >--
using System.IO; //Folder, Directory
//--</ using >--
|
In diesem Beispiel werden für alle Fotos in einem Verzeichnis automatisch Unter-Ordner erstellt, welche das gleiche Erstellungsdatum der Fotos haben.
Betrifft: WPF, Directory, Verzeichnisse, Ordner, Dateien
Visual Studio
Breakpoint bei CreateDirectory:
Wenn der Pfad nicht existiert, dann wird der neue Unterordner erstellt mit CreateDirectory
Hinweis: Das Datum eines Foto von einer Kamera steht in der LastWriteTime Eigenschaft und nicht in CreationTime.
Unter CreationTime wird hier das Datum verstanden, welches zum Übertragen von der Kamera auf einen Computer oder Festplatte stattgefunden hat
Kompletter Beispiel-Code in C#
//----< Selected Folder >----
//< Selected Path >
String sPath = "C:\\_Daten\\Desktop\\Test_Fotos"; // folderDialog.SelectedPath;
tbxFolder.Text = sPath;
//</ Selected Path >
//--------< Folder >--------
DirectoryInfo folder = new DirectoryInfo(sPath);
if (folder.Exists)
{
//------< @Loop: Files >------
foreach (FileInfo fileInfo in folder.GetFiles())
{
//----< File >----
String sDate = fileInfo.LastWriteTime.ToString("yyyy-MM-dd");
Debug.WriteLine("#Debug: File: " + fileInfo.Name + " Date:" + sDate);
//--< check and create Directory >--
//*if subfolder does not exist then create one
String sPath_SubDirectory = folder.FullName + "\\" + sDate;
if (Directory.Exists(sPath_SubDirectory)==false )
{ Directory.CreateDirectory(sPath_SubDirectory); }
//--</ check and create Directory >--
//DirectoryInfo subFolder = folder.GetDirectories(sDate, SearchOption.TopDirectoryOnly);
//if (subFolder)
//----</ File >----
}
//------</ @Loop: Files >------
}
//--------</ Folder >--------
//----</ Selected Folder >----
|