Moving all files in a directory vb.net

  • Thread starter Thread starter smreid
  • Start date Start date
S

smreid

Guest
Hi,

I am a newbie to vb and am having a few problems with a simple application I am writing. The application shows some radio buttons on a form and creates a directory based on the the selected buttons. What I want to do next is move files from one directory into the created directory. I do not know the filenames or the amount of files in the directory.

Can anyone help?

Thanks

smreid
 
Code:
/// <summary>
/// Moves the path dir to the destination dir.  For the destination dir you must include a new folder name. 
/// You cannot just move to an existing folder.  Returns true if successful.  Another thing to remember is that
/// if a folder is empty it will not create it in the destination if the destination is another drive. For errors,
/// it produces a log called DeleteDirLog. You test to see if it has any errors by if its length is greater than
/// the static variable accessError. Ex: if(DeleteDirLog.Length > accessError.Length). Note, that log is the log
/// that is produced by DeleteDir() because this method uses it. So, it is only for files that werent deleted.
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
		public bool MoveDir(string sourceDir, string destination)
		{
			string drive= destination.Substring(0, 3); //check if drive is the same.
			if(! sourceDir.StartsWith(drive) || sourceDir.StartsWith("\\") || destination.StartsWith("\\"))
			{
				string[]Fs= Directory.GetFileSystemEntries(sourceDir);
				foreach(string x in Fs)
				{
					if(!Directory.Exists(destination))  Directory.CreateDirectory(destination);
					if(Directory.Exists(x))
						MoveDir(x, destination+"\\"+Path.GetFileName(x));
					else 
						File.Copy(x, destination+"\\"+Path.GetFileName(x));
				}
				this.DeleteDir(sourceDir);  return true;
			}
				
			if(!Directory.Exists(destination) && Directory.Exists(sourceDir))
				try{Directory.Move(sourceDir, destination);}
				catch{MessageBox.Show("Move was unsuccessful.\nMake sure the directory is not in use or try a reboot.", "Error");
					return false;}
			else 
			{
				MessageBox.Show("Destination already exists or source dir does not exist, cannot move.", "Error");
				return false;
			}
			return true;
		}

C# is almost just like vb.net and there are C# to VB translators on the net you can use to get the VB.net equiv of that code.
 
Back
Top