将文件复制到创建的目录中

Copy a file into a created directory

我正在做一个项目,我想根据文本字段值生成一个目录,我想将一个文件复制到创建的文件夹中...到目前为止,我可以创建目录并复制文件但进入创建的文件夹....

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

您有以下代码:

string destination = "C:\Users\prashan\Desktop\" 
    + System.IO.Directory.CreateDirectory(id) + File_name;

您将 CreateDirectory() 的结果连接到您的目标文件名中,这是不正确的。相反,您可以将其拆分为两个操作,如下所示:

System.IO.Directory.CreateDirectory("C:\Users\prashan\Desktop\" + id);
string destination = "C:\Users\prashan\Desktop\" + id + "\" + File_name;

这不是最干净的方法,使用 Path.Combine() 会更好,但我想尽可能少地更改您的代码。

代码中的小改动。修改目标路径使其成为有效路径。

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