How to copy a file to pre-destinated folder using File.OpenDialog?

2.2k views Asked by At

Using File.OpenDialog how can i make a copy of selected files to a certain (predeclared or even better from a string variable taken from textbox) location? I assume i can firstly simply use the ofd method, but where to determine the location to copy?

InitializeComponent();

PopulateTreeView();

this.treeView1.NodeMouseClick +=
    new TreeNodeMouseClickEventHandler(this.treeView1_NodeMouseClick);

OpenFileDialog ofd1 = new OpenFileDialog();

and for the button:

private void button3_Click(object sender, EventArgs e)
{
    if (ofd1.ShowDialog() == DialogResult.OK)
    { }
}
2

There are 2 answers

0
TheMi7ch On

Check out the foreach loop in this for iterating through all of the files you selected using the OpenDialog.

I think this is what you're looking for in regards to actually copying the files. It takes a source directory and copies to the destination you provide.

0
Yogi On

If I understood correctly, then once you select the file from open file dialog, you want to copy it to a certain location. Then you can use something like this code -

        if (this.openFileDialog1.ShowDialog()== System.Windows.Forms.DialogResult.OK)
        {
            var fileName = this.openFileDialog1.FileName;
            File.Copy(fileName, "DestinationFilePath");
        }

Or in case of multiple selected file, something like this -

        if (this.openFileDialog1.ShowDialog()== System.Windows.Forms.DialogResult.OK)
        {
            var fileNames = this.openFileDialog1.FileNames;

            foreach (var fileName in fileNames)
            {
                File.Copy(fileName, "DestinationFilePath/" + fileName);
            }
        }