Folder copy

Cine

Mitglied
Hiho, meine Wenigkeit schon wieder.

Gibt es eigetlich eine Funktion wie File.copy(quell,ziel) für komplette Ordner?

Mit dem File.copy bekomme ich irgendwie ne Fehlermeldung das er die Quelle nicht findet obwohl ne MassageBox den richtigen Pfad ausgibt.
Also gehe ich mal davon aus das es was extra gibt für komplette Folder...

Könnt Ihr mir da weiter helfen find irgendwie nichts gescheites dazu.
 
Hallo

Du kanst einen kompletten Ordner mit Directory.Move verschieben.

Aber wenn du einen Kompletten Ordner kopieren willst, must du den Ordner Rekrusiv durgehen und die Ordner einzeln erstellen. Danach alle Datein zu den Bestimmungsort kopieren.

Eine Direkte Mothode gibt es meines Wissens nitcht.
 
Hm,

hab ich mir schon fast gedacht, dass es da nicht so einfach ist wie bei den Files :)

Da stellt sich mir schon gleich die nächste Frage obs da nicht einfacher ist einen saveDialog zu machen, wo der Benutzer den Kram selber machen kann. Obwohl des nicht ganz so der Sinn ist. Der sollte eigetlich nur copy sagen und dann sollte des Proggier das machen....

Hast du für diesen rekrusiven Lösungsvorschlag eine Strategie oder vielleicht mal ein Beispiel bei dem ich ein bischen spicken kann?

Wäre super. Hab da echt (noch) keine Ahnung von.
 
Black_Deal hat gesagt.:
Eine Direkte Mothode gibt es meines Wissens nitcht.
Aber hier im Foum. -->Suchfunktion

// Edit: Ich war mir eigentlich sicher das der Quellcode für's kopieren noch im Forum ist.
Code:
public class DirectoryCopy {

	public static void Main() {
		new DirectoryCopy();
	}

	private string sourcepath, destpath;
	ArrayList CollectedFiles = new ArrayList();

	public DirectoryCopy() {
		Console.Write("SourcePath: "); sourcepath = Console.ReadLine();
		Console.Write("Dest.Path: "); destpath = Console.ReadLine();
		Copy(sourcepath);
		Console.Read();
	}

	private void Copy(string dir) {

		if (Directory.Exists(dir)) {

			foreach (string subdir in Directory.GetDirectories(dir)) {
				Copy(subdir);
			}

			string dest = dir.Replace(sourcepath, destpath);
			Directory.CreateDirectory(dest);
			Console.WriteLine("Create Directory: " + dest);

			foreach (string file in Directory.GetFiles(dir)) {
				string newfile = file.Replace(sourcepath, destpath);
				File.Copy(file, newfile);
				Console.WriteLine("Copy File " + file + " to " + newfile);
			}
		}
	}

	private void Search ( string Dir, string FileTag ) {

		if ( Directory.Exists( Dir )){

			foreach (string SubDir in Directory.GetDirectories( Dir )) {
				Search( SubDir, FileTag );
			}

			foreach ( string File in Directory.GetFiles( Dir )){
				if ( File.Substring( File.IndexOf( "." ) ) == FileTag )
					CollectedFiles.Add( File );
			}
		}
	}
}

MfG cosmo
 
Zuletzt bearbeitet:
Hab es jetzt so ist deinem ziemlich ähnlich:

Code:
  public static void filework(string source, string destination)
  		{
  			// Ordner durchgehen
 			foreach (string folder in Directory.GetDirectories(source))
  			{
  				// Ordnername extrahieren
 				int index = folder.LastIndexOf("\\");
 				string cop = folder.Substring(index+1);
 				Directory.CreateDirectory(destination + "\\" + cop);
  				// rekursiver aufruf
 				filework(folder,destination + "\\" + cop);
  			}
  			// Dateien durchgehen
  			foreach (string filename in Directory.GetFiles(source))
  			{
 		 		int index = filename.LastIndexOf("\\");
 		 		string cop = filename.Substring(index+1);
 		 		if (File.Exists(destination + "\\" + cop))
  					{
 		 		 File.Delete(destination + "\\" + cop);
 		 		 File.Copy(filename,destination + "\\" + cop);
  					}
  					else
  					{
 		 		 File.Copy(filename,destination + "\\" + cop);
  					}
  			}
  
  	   }
 
Es gibt da wirklich viele Möglichkeiten sich die Rekursion auszutüfteln.
Das Beispiel war von Norbert Eder oder Alexander Schuc. Weiss nicht mehr genau.

Tipp:
Die doppelten Slashes kannst Du dir spaaren:
Code:
LastIndexOf( @"\" )
Das @ bewirkt das die Escape-Sequenzen nicht beachtet werden.
Alternativ gibt es noch den
Code:
Path.DirectorySeparatorChar
Code:
destination + "\\" + cop
könntest Du das dann z.B. auch so
Code:
string.Format("{0}{1}{2}", destination, Path.DirectorySeparatorChar, cop)
schreiben.
Vorrausgesetzt Du gewöhnst Dir mal Boxing an. Das verketten von Stings sieht nicht nur unsauber aus, sondern ist auch langsam.
(bin mir zumindest sicher das ich Das mal in der MSDN gelesen hab).

MfG cosmo
 
Das @ bewirkt nicht, dass Escape-Sequenzen nicht beachtet werden, sondern dass du als Programmierer sie nicht beachten musst. Intern werden die entsprechenden Chars sehr wohl entsprechend behandelt.
 
Wenn des Proggie mal fertig ist werde ich des ma ausprobieren mit dem @....
Aber erstmal muss des fertig werden damit Cheffe endlich Ruhe gibt. ~g~

Weiß zwar noch net wie ich den nächsten Schritt machen soll, aber mal sehen.

Muss noch einbauen, dass eine html bearbeitet wird. bestimmten punkt suchen, finden, eine Zeile löschen und eine andere hinzufügen....

Naja ma gucken.... newbe halt kann alles etwas dauern bis es klappt. Das wie ist garnicht meinProblem hängt meist an der Umsetzung. Mir fehlen noch zu viele Befehle im Kopf. Aber Übung macht den Meister.

Aber thx noch mal für Eure Hilfe.
 
Wie schon im anderen Thread angekündigt hier meine Version


Erstmal die Orignal VB.NET Funktion http://www.bubble-media.com/cgi-bin/articles/archives/000026.html
Visual Basic:
' Recursively copy all files and subdirectories from the
' specified source to the specified destination.
Private Sub RecursiveCopyFiles( _
ByVal sourceDir As String, _
ByVal destDir As String, _
ByVal fRecursive As Boolean, ByVal overWrite As Boolean)
Dim i As Integer
Dim posSep As Integer
Dim sDir As String
Dim aDirs() As String
Dim sFile As String
Dim aFiles() As String
' Add trailing separators to the supplied paths if they don't exist.
If Not sourceDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) Then
sourceDir &= System.IO.Path.DirectorySeparatorChar
End If
If Not destDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) Then
destDir &= System.IO.Path.DirectorySeparatorChar
End If
' Recursive switch to continue drilling down into dir structure.
If fRecursive Then
' Get a list of directories from the current parent.
aDirs = System.IO.Directory.GetDirectories(sourceDir)
For i = 0 To aDirs.GetUpperBound(0)
' Get the position of the last separator in the current path.
posSep = aDirs(i).LastIndexOf(@"\")
' Get the path of the source directory.
sDir = aDirs(i).Substring((posSep + 1), aDirs(i).Length - (posSep + 1))
' Create the new directory in the destination directory.
System.IO.Directory.CreateDirectory(destDir + sDir)
' Since we are in recursive mode, copy the children also
RecursiveCopyFiles(aDirs(i), (destDir + sDir), fRecursive, overWrite)
Next
End If
' Get the files from the current parent.
aFiles = System.IO.Directory.GetFiles(sourceDir)

' Copy all files.
For i = 0 To aFiles.GetUpperBound(0)
' Get the position of the trailing separator.
posSep = aFiles(i).LastIndexOf(@"\")
' Get the full path of the source file.
sFile = aFiles(i).Substring((posSep + 1), aFiles(i).Length - (posSep + 1))
Try

' Copy the file.
System.IO.File.Copy(aFiles(i), destDir + sFile, False)
addToConsoleWindow("Copied " & sFile & " to " & destDir)
Catch ex As Exception
If overWrite = False Then
errorBoxShow(ex.Message)
addToConsoleWindow("Skipping..." & ex.Message)
Else
System.IO.File.Copy(aFiles(i), destDir + sFile, True)
addToConsoleWindow("Overwriting old " & sFile & " in " & destDir)
End If
End Try
Next i
 
End Sub

Und jetzt noch die auf C# umgebaute Funktion
C#:
    /*Recursively copy all files and subdirectories from the
    specified source to the specified destination.*/
    static void RecursiveCopyFiles(string sourceDir, string destDir, bool fRecursive, bool overWrite)
    {
        int i = 0;
        int posSep = 0;
        string sDir = null;
        string[] aDirs = null;
        string sFile = null;
        string[] aFiles = null;
        /*Add trailing separators to the supplied paths if they don't exist.*/
        if (!sourceDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()))
        {
            sourceDir += System.IO.Path.DirectorySeparatorChar;
        }
        if (!destDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()))
        {
            destDir += System.IO.Path.DirectorySeparatorChar;
        }
        /*Recursive switch to continue drilling down into dir structure.*/
        if (fRecursive) 
        {
            /*Get a list of directories from the current parent.*/
            aDirs = System.IO.Directory.GetDirectories(sourceDir);
            for (i = 0; i<=aDirs.GetUpperBound(0); i++)
            {
                /*Get the position of the last separator in the current path.*/
                posSep = aDirs[i].LastIndexOf(@"\"");
                /*Get the path of the source directory.*/
                sDir = aDirs[i].Substring((posSep + 1), aDirs[i].Length - (posSep + 1));
                /*Create the new directory in the destination directory.*/
                System.IO.Directory.CreateDirectory(destDir + sDir);
    
                /*Since we are in recursive mode, copy the children also*/
                RecursiveCopyFiles(aDirs[i], (destDir + sDir), fRecursive, overWrite);
            }
        }
        
        
        /*Get the files from the current parent.*/
        aFiles = System.IO.Directory.GetFiles(sourceDir);

        /*Copy all files.*/
        for (i = 0; i<= aFiles.GetUpperBound(0); i++)
        {
            /*Get the position of the trailing separator.*/
            posSep = aFiles[i].LastIndexOf(@"\"");
    
            /*Get the full path of the source file.*/
            sFile = aFiles[i].Substring((posSep + 1), aFiles[i].Length - (posSep + 1));
        
            try
            {
                /*Copy the file.*/
                System.IO.File.Copy(aFiles[i], destDir + sFile, false);
                Console.WriteLine("Copied " + sFile + " to " + destDir);
            }    
            catch (Exception ex)
            {   
                if (overWrite == false) 
                {
                    Console.WriteLine("Skipping..." + ex.Message);
                }   
                else
                {
                    System.IO.File.Copy(aFiles[i], destDir + sFile, true);
                    Console.WriteLine("Overwriting old " + sFile + " in " + destDir);
                
                }
            }
        }
    }
^^ACHTUNG: (@"\"") bitte durch (@"\") esrsetzen
Sonst zerstört es aber leider des Highlight
 
Zurück