I have little problem with converting, I try to convert folder where is subfolders but its not creating subfolders, makes only one folder "_converted" and in the folder is all converted subfolder images.
My code:
private void btnConvert_Click(object sender, EventArgs e)
{
string[] originalImage = Directory.GetDirectories(txtFilePath.Text, "*.*",
SearchOption.AllDirectories);
foreach (var directory in originalImage)
{
Debug.WriteLine(directory);
}
foreach (string dir in originalImage)
{
string folderPath = #"C:\test\" + "_converted";
folderPath = folderPath.Substring(folderPath.IndexOf(#"\") + 1);
DirectoryInfo di = Directory.CreateDirectory(folderPath);
if (Directory.Exists(folderPath))
{
DirectoryInfo dInfo = new DirectoryInfo(dir);
foreach (var filename in dInfo.GetFiles())
{
FileInfo fInfo = new FileInfo(filename.FullName);
var fileExtension = fInfo.Extension;
var fileOriginalDate = fInfo.CreationTime;
if (fileExtension.ToUpper() == ".JPG" || fileExtension.ToUpper() == ".PNG")
{
using (Bitmap bitmap = new Bitmap(filename.FullName))
{
string fn = Path.GetFileNameWithoutExtension(filename.FullName);
VariousQuality(bitmap, fn, fileExtension,
fileOriginalDate, folderPath);
}
}
}
}
}
}
I tried to use this method:
folderPath = folderPath.Substring(folderPath.IndexOf(#"\") + 1);
How I can resolve this problem?
You are not handling the folders' names correctly. Try this:
private void btnConvert_Click(object sender, EventArgs e)
{
string[] originalImage = Directory.GetDirectories(txtFilePath.Text, "*.*", SearchOption.AllDirectories);
foreach (var directory in originalImage)
{
Debug.WriteLine(directory);
}
foreach (string dir in originalImage)
{
// The name of the current folder (dir)
// This will convert "C:\Users\User\Desktop\Myfolder\Image1" to simply "Image1" since we create a substring after the LAST backslash ('\')
string folderName = dir.Substring(dir.LastIndexOf('\\') + 1); // Ex. "Image1"
// This will now be "C:\test\FOLDERNAME_converted"
string folderPath = #"C:\test\" + folderName + #"_converted\"; // Ex. "C:\test\image1_converted\";
// This can now create the folders
DirectoryInfo di = Directory.CreateDirectory(folderPath);
// Below is unchanged for now
if (Directory.Exists(folderPath))
{
DirectoryInfo dInfo = new DirectoryInfo(dir);
foreach (var filename in dInfo.GetFiles())
{
FileInfo fInfo = new FileInfo(filename.FullName);
var fileExtension = fInfo.Extension;
var fileOriginalDate = fInfo.CreationTime;
if (fileExtension.ToUpper() == ".JPG" || fileExtension.ToUpper() == ".PNG")
{
using (Bitmap bitmap = new Bitmap(filename.FullName))
{
string fn = Path.GetFileNameWithoutExtension(filename.FullName);
VariousQuality(bitmap, fn, fileExtension,
fileOriginalDate, folderPath);
}
}
}
}
}
}
I Hope this helps.
I just have one question. When getting the directories in your directory path (txtFilePath.Text), you get all folders including subfolders (SearchOptions.AllDirectories). When saving the converted folders to the "C:\test" folder, you don't take into account that a folder could have been a subfolder. Because of this the following problem happens. Let's say you have a folder with a folder with a folder:
"HeadFolder -> Image1 -> Image1.2"
What the program will find:
1. "Path\\To\\Image1"
2. "Path\\To\\Image1.2"
After converting you'll get:
"HeadFolder"
"Image1"
"Image1.2"
Notice that "Image1.2" does NOT end up inside "Image1" as prior to conversion
You're creating the same folder in each iteration of the loop. Just create a folder using the current directory by replacing the below lines:
string folderPath = #"C:\test\" + "_converted";
folderPath = folderPath.Substring(folderPath.IndexOf(#"\") + 1);
With this line:
string folderPath = Path.Combine(#"C:\test\", dir + "_converted");
When we are copying images in one folder to another folder, images are going to copy one by one, then it takes more time when thousands's of images are copying, Is there any Possibility to copy Multiple images at a time? "This is My code"
int avilableCharts = 0;
int unavialableCharts = 0;
string chartid;
int count = 0;
StreamReader rd = new StreamReader(txtFileName.Text);
StreamWriter tw = new StreamWriter("C:\\LogFiles\\SucessfullyMovedImages.txt");
StreamWriter tw1 = new StreamWriter("C:\\LogFiles\\UnavailableImages.txt");
DirectoryInfo dirinfo = new DirectoryInfo(txtSourceFolder.Text);
FileInfo[] file = dirinfo.GetFiles("*.pdf");
while (!rd.EndOfStream)
{
chartid = rd.ReadLine() + ".pdf";
count = count + 1;
worker.ReportProgress(count);
string FName = string.Empty;
if (File.Exists(txtSourceFolder.Text + chartid))
{
File.Copy(txtSourceFolder.Text + chartid , txtDestinationFolder.Text + chartid );
avilableCharts = avilableCharts + 1;
tw.WriteLine(chartid);
}
else
{
unavialableCharts = unavialableCharts + 1;
tw1.WriteLine(chartid);
}
}
tw.Close();
tw1.Close();
MessageBox.Show("Successfully Copied Images are :" + avilableCharts);
MessageBox.Show("Total Unavilable Images are : " + unavialableCharts);
use below code :
public class SimpleFileMove
{
static void Main()
{
string sourceFile = #"C:\Users\Public\public\test.txt";
string destinationFile = #"C:\Users\Public\private\test.txt";
// To move a file or folder to a new location:
System.IO.File.Move(sourceFile, destinationFile);
// To move an entire directory. To programmatically modify or combine
// path strings, use the System.IO.Path class.
System.IO.Directory.Move(#"C:\Users\Public\public\test\", #"C:\Users\Public\private");
}
}
In the below code I want to create 2 subfolders in asp.net. I've tried the following code, but it is not creating sub folder. Please help me to do this.
string Uploadpath = ConfigurationManager.AppSettings["FilePath"];
string sBatchName = System.DateTime.Now.ToString("ddMMMyyyyhhmmss");
string[] sFolder = new string[3];
sFolder[0] = "\\Input\\";
sFolder[1] = "\\Data\\";
string strUploadpath = Uploadpath.TrimEnd("\\".ToCharArray()) + "\\" + sBatchName + "\\";
DirectoryInfo dInfo = new DirectoryInfo(strUploadpath);
if (!dInfo.Exists)
{
dInfo.Create();
}
for (int i = 0; i < sFolder.Length; i++)
{
DirectoryInfo info = new DirectoryInfo(strUploadpath + sFolder[i]);
if (!dInfo.Exists)
{
dInfo.Create();
}
}
for (int i = 0; i < sFolder.Length; i++)
{
DirectoryInfo info = new DirectoryInfo(strUploadpath + sFolder[i]);
if (!info .Exists)
{
info.Create();
}
}
you should use info object instead of dInfo.
You can create a SubDirectory by using
Directory.CreateDirectory(path);
Where path is the path to the current directory
I have a folder that is filled with dwg files so I just need to find the latest version of a File or if a File has no versions then copy it to a directory. For example here are three files:
ABBIE 08-10 #6-09H4 FINAL 06-12-2012.dwg
ABBIE 08-10 #6-09H4 FINAL 06-12-2012_1.dwg
ABBIE 08-10 #6-09H4 FINAL 06-12-2012_2.dwg
Notice the difference is one file has a _1 and another has a _2 so the latest file here is the _2. I need to keep the latest file and copy it to a directory. Some files will not have different versions so those can be copied. I cannot focus on the creation date of the file or the modified date because in many instances they are the same so all I have to go on is the file name itself. I'm sure there is a more efficient way to do this than what I will post below.
DirectoryInfo myDir = new DirectoryInfo(#"H:\Temp\Test");
var Files = myDir.GetFiles("*.dwg");
string[] fileList = Directory.GetFiles(#"H:\Temp\Test", "*FINAL*", SearchOption.AllDirectories);
ArrayList list = new ArrayList();
ArrayList WithUnderscores = new ArrayList();
string nameNOunderscores = "";
for (int i = 0; i < fileList.Length; i++)
{
//Try to get just the filename..
string filename = fileList[i].Split('.')[0];
int position = filename.LastIndexOf('\\');
filename = filename.Substring(position + 1);
filename = filename.Split('_')[0];
foreach (FileInfo allfiles in Files)
{
var withoutunderscore = allfiles.Name.Split('_')[0];
withoutunderscore = withoutunderscore.Split('.')[0];
if (withoutunderscore.Equals(filename))
{
nameNOunderscores = filename;
list.Add(allfiles.Name);
}
}
//If there is a number after the _ then capture it in an ArrayList
if (list.Count > 0)
{
foreach (string nam in list)
{
if (nam.Contains("_"))
{
//need regex to grab numeric value after _
var match = new Regex("_(?<number>[0-9]+)").Match(nam);
if (match.Success)
{
var value = match.Groups["number"].Value;
var number = Int32.Parse(value);
WithUnderscores.Add(number);
}
}
}
int removedcount = 0;
//Whats the max value?
if (WithUnderscores.Count > 0)
{
var maxval = GetMaxValue(WithUnderscores);
Int32 intmax = Convert.ToInt32(maxval);
foreach (FileInfo deletefile in Files)
{
string shorten = deletefile.Name.Split('.')[0];
shorten = shorten.Split('_')[0];
if (shorten == nameNOunderscores && deletefile.Name != nameNOunderscores + "_" + intmax + ".dwg")
{
//Keep track of count of Files that are no good to us so we can iterate to next set of files
removedcount = removedcount + 1;
}
else
{
//Copy the "Good" file to a seperate directory
File.Copy(#"H:\Temp\Test\" + deletefile.Name, #"H:\Temp\AllFinals\" + deletefile.Name, true);
}
}
WithUnderscores.Clear();
list.Clear();
}
i = i + removedcount;
}
else
{
//This File had no versions so it is good to be copied to the "Good" directory
File.Copy(#"H:\Temp\SH_Plats\" + filename, #"H:\Temp\AllFinals" + filename, true);
i = i + 1;
}
}
I've made a Regex based solution, and apparently come late to the party in the meantime.
(?<fileName>[A-Za-z0-9-# ]*)_?(?<version>[0-9]+)?\.dwg
this regex will recognise the fileName and version and split them into groups, a pretty simple foreach loop to get the most recent files in a dictionary (cos I'm lazy) and then you just need to put the fileNames back together again before you access them.
var fileName = file.Key + "_" + file.Value + ".dwg"
full code
var files = new[] {
"ABBIE 08-10 #6-09H4 FINAL 06-12-2012.dwg",
"ABBIE 08-10 #6-09H4 FINAL 06-12-2012_1.dwg",
"ABBIE 08-10 #6-09H4 FINAL 06-12-2012_2.dwg",
"Second File.dwg",
"Second File_1.dwg",
"Third File.dwg"
};
// regex to split fileName from version
var r = new Regex( #"(?<fileName>[A-Za-z0-9-# ]*)_?(?<version>[0-9]+)?\.dwg" );
var latestFiles = new Dictionary<string, int>();
foreach (var f in files)
{
var parsedFileName = r.Match( f );
var fileName = parsedFileName.Groups["fileName"].Value;
var version = parsedFileName.Groups["version"].Success ? int.Parse( parsedFileName.Groups["version"].Value ) : 0;
if( latestFiles.ContainsKey( fileName ) && version > latestFiles[fileName] )
{
// replace if this file has a newer version
latestFiles[fileName] = version;
}
else
{
// add all newly found filenames
latestFiles.Add( fileName, version );
}
}
// open all most recent files
foreach (var file in latestFiles)
{
var fileToCopy = File.Open( file.Key + "_" + file.Value + ".dwg" );
// ...
}
You can use this Linq query with Enumerable.GroupBy which should work(now tested):
var allFiles = Directory.EnumerateFiles(sourceDir, "*.dwg")
.Select(path => new
{
Path = path,
FileName = Path.GetFileName(path),
FileNameWithoutExtension = Path.GetFileNameWithoutExtension(path),
VersionStartIndex = Path.GetFileNameWithoutExtension(path).LastIndexOf('_')
})
.Select(x => new
{
x.Path,
x.FileName,
IsVersionFile = x.VersionStartIndex != -1,
Version = x.VersionStartIndex == -1 ? new Nullable<int>()
: x.FileNameWithoutExtension.Substring(x.VersionStartIndex + 1).TryGetInt(),
NameWithoutVersion = x.VersionStartIndex == -1 ? x.FileName
: x.FileName.Substring(0, x.VersionStartIndex)
})
.OrderByDescending(x => x.Version)
.GroupBy(x => x.NameWithoutVersion)
.Select(g => g.First());
foreach (var file in allFiles)
{
string oldPath = Path.Combine(sourceDir, file.FileName);
string newPath;
if (file.IsVersionFile && file.Version.HasValue)
newPath = Path.Combine(versionPath, file.FileName);
else
newPath = Path.Combine(noVersionPath, file.FileName);
File.Copy(oldPath, newPath, true);
}
Here's the extension method which i'm using to determine if a string is parsable to int:
public static int? TryGetInt(this string item)
{
int i;
bool success = int.TryParse(item, out i);
return success ? (int?)i : (int?)null;
}
Note that i'm not using regex but string methods only.
Try this
var files = new My.Computer().FileSystem.GetFiles(#"c:\to\the\sample\directory", Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, "*.dwg");
foreach (String f in files) {
Console.WriteLine(f);
};
NB: Add a reference to Microsoft.VisualBasic and use the following line at the beginning of the class:
using My = Microsoft.VisualBasic.Devices;
UPDATE
The working sample[tested]:
String dPath=#"C:\to\the\sample\directory";
var xfiles = new My.Computer().FileSystem.GetFiles(dPath, Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, "*.dwg").Where(c => Regex.IsMatch(c,#"\d{3,}\.dwg$"));
XElement filez = new XElement("filez");
foreach (String f in xfiles)
{
var yfiles = new My.Computer().FileSystem.GetFiles(dPath, Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, string.Format("{0}*.dwg",System.IO.Path.GetFileNameWithoutExtension(f))).Where(c => Regex.IsMatch(c, #"_\d+\.dwg$"));
if (yfiles.Count() > 0)
{
filez.Add(new XElement("file", yfiles.Last()));
}
else {
filez.Add(new XElement("file", f));
};
};
Console.Write(filez);
Can you do this by string sort? The only tricky part I see here is to convert the file name to a sortable format. Just do a string replace from dd-mm-yyyy to yyyymmdd. Then, sort the the list and get the last record out.
This is what you want considering fileList contain all file names
List<string> latestFiles=new List<string>();
foreach(var groups in fileList.GroupBy(x=>Regex.Replace(x,#"(_\d+\.dwg$|\.dwg$)","")))
{
latestFiles.Add(groups.OrderBy(s=>Regex.Match(s,#"\d+(?=\.dwg$)").Value==""?0:int.Parse(Regex.Match(s,#"\d+(?=\.dwg$)").Value)).Last());
}
latestFiles has the list of all new files..
If fileList is bigger,use Threading or PLinq
My source path is C:\Music\ in which I have hundreds of folders called Album-1, Album-2 etc.
What I want to do is create a folder called Consolidated in my source path.
And then I want to move all the files inside my albums to the folder Consolidated, so that I get all the music files in one folder.
How can I do this?
Try like this
String directoryName = "C:\\Consolidated";
DirectoryInfo dirInfo = new DirectoryInfo(directoryName);
if (dirInfo.Exists == false)
Directory.CreateDirectory(directoryName);
List<String> MyMusicFiles = Directory
.GetFiles("C:\\Music", "*.*", SearchOption.AllDirectories).ToList();
foreach (string file in MyMusicFiles)
{
FileInfo mFile = new FileInfo(file);
// to remove name collisions
if (new FileInfo(dirInfo + "\\" + mFile.Name).Exists == false)
{
mFile.MoveTo(dirInfo + "\\" + mFile.Name);
}
}
It will get all the files in the "C:\Music" folder (including files in the subfolder) and move them to the destination folder. The SearchOption.AllDirectories will recursively search all the subfolders.
Basically, that can be done with Directory.Move:
try
{
Directory.Move(source, destination);
}
catch { }
don't see any reason, why you shouldn't use this function. It's recursive and speed optimized
You can use the Directory object to do this, but you might run into problems if you have the same file name in multiple sub directories (e.g. album1\1.mp3, album2\1.mp3) so you might need a little extra logic to tack something unique onto the names (e.g. album1-1.mp4).
public void CopyDir( string sourceFolder, string destFolder )
{
if (!Directory.Exists( destFolder ))
Directory.CreateDirectory( destFolder );
// Get Files & Copy
string[] files = Directory.GetFiles( sourceFolder );
foreach (string file in files)
{
string name = Path.GetFileName( file );
// ADD Unique File Name Check to Below!!!!
string dest = Path.Combine( destFolder, name );
File.Copy( file, dest );
}
// Get dirs recursively and copy files
string[] folders = Directory.GetDirectories( sourceFolder );
foreach (string folder in folders)
{
string name = Path.GetFileName( folder );
string dest = Path.Combine( destFolder, name );
CopyDir( folder, dest );
}
}
public void MoveDirectory(string[] source, string target)
{
var stack = new Stack<Folders>();
stack.Push(new Folders(source[0], target));
while (stack.Count > 0)
{
var folders = stack.Pop();
Directory.CreateDirectory(folders.Target);
foreach (var file in Directory.GetFiles(folders.Source, "*.*"))
{
string targetFile = Path.Combine(folders.Target, Path.GetFileName(file));
if (File.Exists(targetFile)) File.Delete(targetFile); File.Move(file, targetFile);
}
foreach (var folder in Directory.GetDirectories(folders.Source))
{
stack.Push(new Folders(folder, Path.Combine(folders.Target, Path.GetFileName(folder))));
}
}
Directory.Delete(source[0], true);
}
}
public class Folders {
public string Source {
get; private set;
}
public string Target {
get; private set;
}
public Folders(string source, string target) {
Source = source;
Target = target;
}
}
Something like this should get you rolling. You'll have to add error checking and what not (What if there is a subdirectory of source named "Consolidated"? What if Consolidated already exists? Etc.) This is from memory, so pardon any syntax errors, etc.
string source = #"C:\Music";
string[] directories = Directory.GetDirectories(source);
string consolidated = Path.Combine(source, "Consolidated")
Directory.CreateDirectory(consolidated);
foreach(var directory in directories) {
Directory.Move(directory, consolidated);
}
private static void MoveFiles(string sourceDir, string targetDir)
{
IEnumerable<FileInfo> files = Directory.GetFiles(sourceDir).Select(f => new FileInfo(f));
foreach (var file in files)
{
File.Move(file.FullName, Path.Combine(targetDir, file.Name));
}
}
You'll probably find this helpful to dedup your mp3's that have a different file name but same title.
source from David # msdn!
byte[] b = new byte[128];
string sTitle;
string sSinger;
string sAlbum;
string sYear;
string sComm;
FileStream fs = new FileStream(file, FileMode.Open);
fs.Seek(-128, SeekOrigin.End);
fs.Read(b, 0, 128);
bool isSet = false;
String sFlag = System.Text.Encoding.Default.GetString(b, 0, 3);
if (sFlag.CompareTo("TAG") == 0)
{
System.Console.WriteLine("Tag is setted! ");
isSet = true;
}
if (isSet)
{
//get title of song;
sTitle = System.Text.Encoding.Default.GetString(b, 3, 30);
System.Console.WriteLine("Title: " + sTitle);
//get singer;
sSinger = System.Text.Encoding.Default.GetString(b, 33, 30);
System.Console.WriteLine("Singer: " + sSinger);
//get album;
sAlbum = System.Text.Encoding.Default.GetString(b, 63, 30);
System.Console.WriteLine("Album: " + sAlbum);
//get Year of publish;
sYear = System.Text.Encoding.Default.GetString(b, 93, 4);
System.Console.WriteLine("Year: " + sYear);
//get Comment;
sComm = System.Text.Encoding.Default.GetString(b, 97, 30);
System.Console.WriteLine("Comment: " + sComm);
}
System.Console.WriteLine("Any key to exit! ");
System.Console.Read();
String directoryName = #"D:\NewAll\";
DirectoryInfo dirInfo = new DirectoryInfo(directoryName);
if (dirInfo.Exists == false)
Directory.CreateDirectory(directoryName);
List<String> AllFiles= Directory
.GetFiles(#"D:\SourceDirectory\", "*.*", SearchOption.AllDirectories).ToList();
foreach (string file in AllFiles)
{
FileInfo mFile = new FileInfo(file);
// to remove name collisions
if (new FileInfo(dirInfo + "\\" + mFile.Name).Exists == false)
{
mFile.MoveTo(dirInfo + "\\" + mFile.Name);
}
else
{
string s = mFile.Name.Substring(0, mFile.Name.LastIndexOf('.'));
int a = 0;
while (new FileInfo(dirInfo + "\\" + s + a.ToString() + mFile.Extension).Exists)
{
a++;
}
mFile.MoveTo(dirInfo + "\\" + s + a.ToString() + mFile.Extension);
}
}
ToCopyIt is important to mention that you can't use the ".move()" method across volumes.
https://learn.microsoft.com/en-us/dotnet/api/system.io.file.move?view=net-6.0
https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.move?view=net-6.0
Move files:
string DirFrom = #"C:\MyWork";
string DirTo = #"E:\Archive";
DirectoryInfo DirInfoFrom = new DirectoryInfo(DirFrom);
DirectoryInfo DirInfoTo = new DirectoryInfo(DirTo);
if (!DirInfoTo.Exists)
{
Directory.CreateDirectory(DirTo);
}
foreach (FileInfo FileToCopy in DirInfoFrom.GetFiles())
{
FileToCopy.CopyTo(DirTo + FileToCopy.Name);
File.Delete(FileToCopy.FullName);
}
Tested 1/31/22 .NET4.8 VS2019
Copy all the folders (nested or not) including their files to another folder (destination) with one function call (static void CopyDirectory(string sourceDir, string destinationDir, bool recursive)):
https://learn.microsoft.com/en-us/dotnet/standard/io/how-to-copy-directories
We already had variant for copying directory structure, so this is just modified version of it for moving:
public static void MoveInner(string sourceDirName, string destDirName, bool moveSubDirs)
{
var dir = new DirectoryInfo(sourceDirName);
var dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory does not exist, create it
if (!Directory.Exists(destDirName))
Directory.CreateDirectory(destDirName);
// Get the file contents of the directory to copy
var files = dir.GetFiles();
foreach (var file in files)
{
// Create the path to the new copy of the file
var temppath = Path.Combine(destDirName, file.Name);
// Move the file.
file.MoveTo(temppath);
}
// If copySubDirs is true, copy the subdirectories
if (!moveSubDirs)
return;
foreach (var subdir in dirs)
{
// Create the subdirectory
var temppath = Path.Combine(destDirName, subdir.Name);
// Move the subdirectories
MoveInner(subdir.FullName, temppath, moveSubDirs: true);
}
}
You loop through them and then simply run Move, the Directory class have functionality for listing contents too iirc.
MSDN : msdn.microsoft.com/en-us/library/bb762914.aspx
private void DirectoryCopy(
string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception.
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory does not exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the file contents of the directory to copy.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
// Create the path to the new copy of the file.
string temppath = Path.Combine(destDirName, file.Name);
// Copy the file.
file.CopyTo(temppath, false);
}
// If copySubDirs is true, copy the subdirectories.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
// Create the subdirectory.
string temppath = Path.Combine(destDirName, subdir.Name);
// Copy the subdirectories.
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
class Program
{
static void Main(string[] args)
{
movedirfiles(#"E:\f1", #"E:\f2");
}
static void movedirfiles(string sourdir,string destdir)
{
string[] dirlist = Directory.GetDirectories(sourdir);
moveallfiles(sourdir, destdir);
if (dirlist!=null && dirlist.Count()>0)
{
foreach(string dir in dirlist)
{
string dirName = destdir+"\\"+ new DirectoryInfo(dir).Name;
Directory.CreateDirectory(dirName);
moveallfiles(dir,dirName);
}
}
}
static void moveallfiles(string sourdir,string destdir)
{
string[] filelist = Directory.GetFiles(sourdir);
if (filelist != null && filelist.Count() > 0)
{
foreach (string file in filelist)
{
File.Copy(file, string.Concat(destdir, "\\"+Path.GetFileName(file)));
}
}
}
}