简体   繁体   中英

Copy a file into a created directory

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);
}  

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.

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);
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM