6 Replies - 443 Views - Last Post: 22 July 2012 - 02:00 PM Rate Topic: -----

#1 burgo857  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 16
  • Joined: 02-June 12

C# Define a folder and copy it using a string?

Posted 19 July 2012 - 03:17 AM

Hey,

I made a program and used hard coded directories while in the making of it.

It is now complete and i was wandering if i can possibly get some help.

On one of my buttons i was copying a folder from one location to another. I was using the following formula:
                    //Copy Folder
                    if (Directory.Exists(@"C:\PROGRA~1\OLD\Docs"))
                        Directory.Delete(@"C:\PROGRA~1\OLD\Docs", true);
                    {
                        foreach (string dirPath in Directory.GetDirectories(@"C:\PROGRA~1\NEW\Docs", "*", SearchOption.AllDirectories))
                            Directory.CreateDirectory(dirPath.Replace(@"C:\PROGRA~1\NEW\Docs", @"C:\PROGRA~1\OLD\Docs"));
                        foreach (string newPath in Directory.GetFiles(@"C:\PROGRA~1\NEW\Docs", "*.*", SearchOption.AllDirectories))
                            File.Copy(newPath, newPath.Replace(@"C:\PROGRA~1\NEW\Docs", @"C:\PROGRA~1\OLD\Docs"));
                    }


So in the the above i remove the old folder, copy all subfolders and files in NEW to OLD. However now that i am not using the hardcoded path how would i determine it now?

I use this for my new paths:
string programFiles = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86);

            string NEW = Path.Combine(programFiles, @"NEW");
            string Docs = Path.Combine(NEW, @"Docs");


Is their a way i can use
string Docs = Path.Combine(WolfETFolder, @"Docs");
in the first method i posted? or a work around that uses program files for 32bit and 64?

Is This A Good Question/Topic? 0
  • +

Replies To: C# Define a folder and copy it using a string?

#2 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 4880
  • View blog
  • Posts: 11,270
  • Joined: 16-October 07

Re: C# Define a folder and copy it using a string?

Posted 19 July 2012 - 05:56 AM

Methods are your friends. Take your code and replace the hard coded stuff with variables.

CopyFolder(@"C:\PROGRA~1\NEW\Docs", @"C:\PROGRA~1\OLD\Docs");

void CopyFolder(string srcDir, string dstDir) {
	if (Directory.Exists(dstDir)) { // alway use braces, even when you don't have to
		Directory.Delete(dstDir, true);
	}
	// however, the braces here have no meaning
	// {
	foreach (string dirPath in Directory.GetDirectories(srcDir, "*", SearchOption.AllDirectories)) {
		Directory.CreateDirectory(dirPath.Replace(srcDir, dstDir));
	}
	foreach (string newPath in Directory.GetFiles(srcDir, "*.*", SearchOption.AllDirectories)) {
		File.Copy(newPath, newPath.Replace(srcDir, dstDir));
	}
	// }
}


For testing, I wrote this:
public void CopyFolderTest(string srcDir, string dstDir) {
	if (Directory.Exists(dstDir)) { Directory.Delete(dstDir, true); }
	foreach (string dirPath in Directory.GetDirectories(srcDir, "*", SearchOption.AllDirectories)) {
		Debug.WriteLine("Directory.CreateDirectory(" + dirPath.Replace(srcDir, dstDir) + ");");
	}
	foreach (string newPath in Directory.GetFiles(srcDir, "*.*", SearchOption.AllDirectories)) {
		Debug.WriteLine("File.Copy(" + newPath + "," + newPath.Replace(srcDir, dstDir) + ");");
	}
}




I noticed that your code seems to not create the root directory, dstDir, which probably isn't good. Also, I'd avoid two separate loops. Objects can be helpful here.

e.g.
public void CopyFolderTest(string srcDirPath, string dstDirPath) {
	DirectoryInfo srcDir = new DirectoryInfo(srcDirPath);
	DirectoryInfo dstDir = new DirectoryInfo(dstDirPath);
	if (dstDir.Exists) { Directory.Delete(dstDir.FullName, true); }
	// you probably want this too
	// dstDir.Create();
	
	foreach (string pathFrom in Directory.GetDirectories(srcDir.FullName, "*", SearchOption.AllDirectories)) {
		DirectoryInfo dirFrom = new DirectoryInfo(pathFrom);
		// Debug.WriteLine(dirFrom.FullName);
		// Debug.WriteLine(dirFrom.FullName.Substring(srcDir.FullName.Length+1));
		DirectoryInfo dirTo = new DirectoryInfo(Path.Combine(dstDir.FullName, dirFrom.FullName.Substring(srcDir.FullName.Length + 1)));
		//Debug.WriteLine(dirTo.FullName);
		Debug.WriteLine("Directory.CreateDirectory(" + dirTo.FullName + ");");
		// dirTo.Create();
		
		foreach(FileInfo file in dirFrom.GetFiles()) {
			//file.CopyTo(Path.Combine(dirFrom.FullName, file.Name));
			Debug.WriteLine("file.CopyTo((" + Path.Combine(dirFrom.FullName, file.Name) + ");");
		}
	}
}



Noice, once you're in a folder, you work there. It seems easier.

In the interests of full disclosure, I'd do this with recursion. Your GetDirectories is using recursion. So is that delete folder.

To given an idea, here's a recursive function to list all directories and contents.
public void ShowFolder(string path) {
	ShowFolder(new DirectoryInfo(path), "");
}

public void ShowFolder(DirectoryInfo di, string indent) {
	Debug.WriteLine(indent + di.FullName);
	foreach (FileInfo file in di.GetFiles()) {
		Debug.WriteLine(indent + " -" + file.Name);
	}
	foreach (DirectoryInfo subDir in di.GetDirectories()) {
		ShowFolder(subDir, indent + "   ");
	}
}



Hope this helps.
Was This Post Helpful? 1
  • +
  • -

#3 Skydiver  Icon User is online

  • Code herder
  • member icon

Reputation: 1896
  • View blog
  • Posts: 5,687
  • Joined: 05-May 12

Re: C# Define a folder and copy it using a string?

Posted 19 July 2012 - 07:22 AM

Please, use the long version of the filename. @"C:\PROGRA~1\NEW\Docs" should be "C:\Program Files\NEW\Docs".

The character after the tilde may not always be a 1 on everybody's computer.

The "Program Files" directory also may not always be on the C drive either, nor may it always be named that. Use the Environment.GetFolderPath() method instead.

And one last thing... Storing user data under the Program Files directory is a really bad idea because the user now needs to run elevated to be able to write into the folder. Store in the ApplicationData or LocalApplicationData folders instead.

This post has been edited by Skydiver: 19 July 2012 - 07:22 AM

Was This Post Helpful? 2
  • +
  • -

#4 burgo857  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 16
  • Joined: 02-June 12

Re: C# Define a folder and copy it using a string?

Posted 20 July 2012 - 03:01 AM

View Postbaavgai, on 19 July 2012 - 05:56 AM, said:

Methods are your friends. Take your code and replace the hard coded stuff with variables.

CopyFolder(@"C:\PROGRA~1\NEW\Docs", @"C:\PROGRA~1\OLD\Docs");

void CopyFolder(string srcDir, string dstDir) {
	if (Directory.Exists(dstDir)) { // alway use braces, even when you don't have to
		Directory.Delete(dstDir, true);
	}
	// however, the braces here have no meaning
	// {
	foreach (string dirPath in Directory.GetDirectories(srcDir, "*", SearchOption.AllDirectories)) {
		Directory.CreateDirectory(dirPath.Replace(srcDir, dstDir));
	}
	foreach (string newPath in Directory.GetFiles(srcDir, "*.*", SearchOption.AllDirectories)) {
		File.Copy(newPath, newPath.Replace(srcDir, dstDir));
	}
	// }
}


For testing, I wrote this:
public void CopyFolderTest(string srcDir, string dstDir) {
	if (Directory.Exists(dstDir)) { Directory.Delete(dstDir, true); }
	foreach (string dirPath in Directory.GetDirectories(srcDir, "*", SearchOption.AllDirectories)) {
		Debug.WriteLine("Directory.CreateDirectory(" + dirPath.Replace(srcDir, dstDir) + ");");
	}
	foreach (string newPath in Directory.GetFiles(srcDir, "*.*", SearchOption.AllDirectories)) {
		Debug.WriteLine("File.Copy(" + newPath + "," + newPath.Replace(srcDir, dstDir) + ");");
	}
}




I noticed that your code seems to not create the root directory, dstDir, which probably isn't good. Also, I'd avoid two separate loops. Objects can be helpful here.

e.g.
public void CopyFolderTest(string srcDirPath, string dstDirPath) {
	DirectoryInfo srcDir = new DirectoryInfo(srcDirPath);
	DirectoryInfo dstDir = new DirectoryInfo(dstDirPath);
	if (dstDir.Exists) { Directory.Delete(dstDir.FullName, true); }
	// you probably want this too
	// dstDir.Create();
	
	foreach (string pathFrom in Directory.GetDirectories(srcDir.FullName, "*", SearchOption.AllDirectories)) {
		DirectoryInfo dirFrom = new DirectoryInfo(pathFrom);
		// Debug.WriteLine(dirFrom.FullName);
		// Debug.WriteLine(dirFrom.FullName.Substring(srcDir.FullName.Length+1));
		DirectoryInfo dirTo = new DirectoryInfo(Path.Combine(dstDir.FullName, dirFrom.FullName.Substring(srcDir.FullName.Length + 1)));
		//Debug.WriteLine(dirTo.FullName);
		Debug.WriteLine("Directory.CreateDirectory(" + dirTo.FullName + ");");
		// dirTo.Create();
		
		foreach(FileInfo file in dirFrom.GetFiles()) {
			//file.CopyTo(Path.Combine(dirFrom.FullName, file.Name));
			Debug.WriteLine("file.CopyTo((" + Path.Combine(dirFrom.FullName, file.Name) + ");");
		}
	}
}



Noice, once you're in a folder, you work there. It seems easier.

In the interests of full disclosure, I'd do this with recursion. Your GetDirectories is using recursion. So is that delete folder.

To given an idea, here's a recursive function to list all directories and contents.
public void ShowFolder(string path) {
	ShowFolder(new DirectoryInfo(path), "");
}

public void ShowFolder(DirectoryInfo di, string indent) {
	Debug.WriteLine(indent + di.FullName);
	foreach (FileInfo file in di.GetFiles()) {
		Debug.WriteLine(indent + " -" + file.Name);
	}
	foreach (DirectoryInfo subDir in di.GetDirectories()) {
		ShowFolder(subDir, indent + "   ");
	}
}



Hope this helps.


I understand my question hasn't been written correctly... If i wanted to copy a folder contents and its subfolders/files to another directory How do i do it without hardcoded paths?

I was using this:
void CopyFolder(string srcDir, string dstDir) {
	if (Directory.Exists(dstDir)) { // alway use braces, even when you don't have to
		Directory.Delete(dstDir, true);
	}
	// however, the braces here have no meaning
	// {
	foreach (string dirPath in Directory.GetDirectories(srcDir, "*", SearchOption.AllDirectories)) {
		Directory.CreateDirectory(dirPath.Replace(srcDir, dstDir));
	}
	foreach (string newPath in Directory.GetFiles(srcDir, "*.*", SearchOption.AllDirectories)) {
		File.Copy(newPath, newPath.Replace(srcDir, dstDir));
	}
	// }
}  


For hardcoded paths. Can i use the copy method above using SpecialFolders Enum?

If so how do i go it? I couldnt wokr it out:(
Was This Post Helpful? 0
  • +
  • -

#5 burgo857  Icon User is offline

  • New D.I.C Head

Reputation: -1
  • View blog
  • Posts: 16
  • Joined: 02-June 12

Re: C# Define a folder and copy it using a string?

Posted 22 July 2012 - 01:37 AM

Is it possible to copy a folder and its subfolders and files within subfolders using this formula:
{
	    foreach (string dirPath in Directory.GetDirectories(srcDir, "*", SearchOption.AllDirectories)) {
	        Directory.CreateDirectory(dirPath.Replace(srcDir, dstDir));
	    }
	    foreach (string newPath in Directory.GetFiles(srcDir, "*.*", SearchOption.AllDirectories)) {
	        File.Copy(newPath, newPath.Replace(srcDir, dstDir))
}


BUT uinstead of HARDCODED PATHS can you use specialfolders enum?

If you can use specialfolders enum for this method how do you do it? i have tried and failed many times... Or is their an easier way?
Was This Post Helpful? 0
  • +
  • -

#6 tlhIn`toq  Icon User is offline

  • Closing in on 5,000
  • member icon

Reputation: 4926
  • View blog
  • Posts: 10,461
  • Joined: 02-June 10

Re: C# Define a folder and copy it using a string?

Posted 22 July 2012 - 01:44 AM

Yes you can use the SpecialFolders enums.

Let's see our failed attempt(s) and we'll try to get you back on the right path.


Some of my common tips (some may apply more than others to your specific style):
  • You have to program as if everything breaks, nothing works, the cyberworld is not perfect, the attached hardware is flakey, the network is slow and unreliable, the harddrive is about to fail, every method will return an error and every user will do their best to break your software. Confirm everything. Range check every value. Make no assumptions or presumptions.

  • Take the extra 3 seconds to rename your controls each time you drag them onto a form. The default names of button1, button2... button54 aren't very helpful. If you rename them right away to something like btnOk, btnCancel, btnSend etc. it helps tremendously when you make the methods for them because they are named after the button by the designer.btnSend_Click(object sender, eventargs e) is a lot easier to maintain than button1_click(object sender, eventargs e)

  • You aren't paying for variable names by the byte. So instead of variables names of a, b, c go ahead and use meaningful names like index, timeOut, row, column and so on. You should avoid 'T' for the timer. Amongst other things 'T' is commonly used throughout C# for Type and this will lead to problems. There are naming guidelines you should follow so your code confirms to industry standards. It makes life much easier on everyone around you, including those of us here to help. If you start using the standards from the beginning you don't have to retrain yourself later.
    You might want to look at some of the naming guidelines. Its a lot easier to start with good habits than to break bad habits later and re-learn.



  • Try to avoid having work actually take place in GUI control event handlers. It is better to have the GUI handler call other methods so those methods can be reused and make the code more readible.
    Spoiler


  • Don't replace lines of code that don't work. Instead comment them out and put your new attemps below that. This will keep you from re-trying the same ideas over and over. Also, when you come back to us saying "I've tried this 100 different ways and still can't get it", we can actually see what you tried. So often a failed attempt is very very close and just needs a little nudge in the right direction. So if we can say "See what you did in attempt 3... blah blah" it helps a lot

    Spoiler

Was This Post Helpful? 1
  • +
  • -

#7 JackOfAllTrades  Icon User is offline

  • Saucy!
  • member icon

Reputation: 5667
  • View blog
  • Posts: 22,509
  • Joined: 23-August 08

Re: C# Define a folder and copy it using a string?

Posted 22 July 2012 - 02:00 PM

Merged with previous, pretty much identical topic.

Quote

Let's see our failed attempt(s) and we'll try to get you back on the right path.


Quoted for truth. As you can see with the merge, you haven't demonstrated you've tried anything at all.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1