Reputation: 7
I'm working on a project where I want a directory to be generated according to a textfield value and I want to copy a file into the created folder...So far I could able to create the directory and copy the file but into the created folder....
try
{
string id = textBox4.Text.Trim();
// Directory.CreateDirectory("C:\\Users\\prashan\\Desktop\\"+id);
string source = null;
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog()==System.Windows.Forms.DialogResult.OK)
{
source = ofd.FileName;
MessageBox.Show(source);
}
string File_name = Path.GetFileName(source);
string destination = "C:\\Users\\prashan\\Desktop\\" +
System.IO.Directory.CreateDirectory(id) + File_name;
System.IO.File.Copy(source, destination);
MessageBox.Show("Done....");
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
Upvotes: 0
Views: 86
Reputation: 7812
Small change in your code. Destination path modified to make it valid path.
try
{
string id = textBox4.Text.Trim();
Directory.CreateDirectory("C:\\Users\\prashan\\Desktop\\"+id);
string source = null;
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
source = ofd.FileName;
MessageBox.Show(source);
}
string File_name = Path.GetFileName(source);
string destination = "C:\\Users\\prashan\\Desktop\\" + id +"\\"+ File_name;
System.IO.File.Copy(source, destination);
MessageBox.Show("Done....");
}
catch (Exception ex)
{
MessageBox.Show(ex.StackTrace);
}
Upvotes: 0
Reputation: 3002
You have the following code:
string destination = "C:\\Users\\prashan\\Desktop\\"
+ System.IO.Directory.CreateDirectory(id) + File_name;
You are concatenating the result of CreateDirectory() into your destination filename, which is incorrect. Instead, you could split this into two operations, like this:
System.IO.Directory.CreateDirectory("C:\\Users\\prashan\\Desktop\\" + id);
string destination = "C:\\Users\\prashan\\Desktop\\" + id + "\\" + File_name;
This isn't the cleanest way to do this, using Path.Combine() would be better, but I wanted to change your code as little as possible.
Upvotes: 1