- Back to Home »
- C#.NET »
- C#.NET code to move files from one folder/directory to other folder with matching file name
Posted by :
Sudhir Chekuri
Saturday, 5 October 2013
Here is the C#.NET code written in windows application which move all files with matching file name from one folder to other folder/directory.Source and destination folder paths are taken from the user from two textboxes in this example.abc* is used in the line12 which means all the files with file name that starts with abc are moved.
Use a button and two textboxes.
In buttonclick event call the below method named as movefiles.
textbox1 is used to get source directory/folder path and textbox2 is used to get the destination folder/directory path.
In buttonclick event call the below method named as movefiles.
textbox1 is used to get source directory/folder path and textbox2 is used to get the destination folder/directory path.
C#.NET code
public void movefiles()
{
try
{
if ((textBox1.Text).Trim() == "" || (textBox2.Text).Trim() == "")
{
MessageBox.Show("Paths shouldn't be empty");
}
else
{
DirectoryInfo dir = new DirectoryInfo(textBox1.Text);
var files = dir.GetFiles("abc*");
int i = files.Count();
if (i > 0)
{
foreach (var file in files)
{
string filename = file.ToString();
string destinationfile = System.IO.Path.Combine(textBox2.Text, filename);
System.IO.File.Move(textBox1.Text + "/" + filename, destinationfile);
}
} MessageBox.Show("Successfully moved from source to destination path");
}
}
catch (Exception ex)
{ MessageBox.Show (ex.Message); }
}
{
try
{
if ((textBox1.Text).Trim() == "" || (textBox2.Text).Trim() == "")
{
MessageBox.Show("Paths shouldn't be empty");
}
else
{
DirectoryInfo dir = new DirectoryInfo(textBox1.Text);
var files = dir.GetFiles("abc*");
int i = files.Count();
if (i > 0)
{
foreach (var file in files)
{
string filename = file.ToString();
string destinationfile = System.IO.Path.Combine(textBox2.Text, filename);
System.IO.File.Move(textBox1.Text + "/" + filename, destinationfile);
}
} MessageBox.Show("Successfully moved from source to destination path");
}
}
catch (Exception ex)
{ MessageBox.Show (ex.Message); }
}