简体   繁体   中英

Cant copy files from one dir to another

I have written a function of copy to copy files from one dir to another but keep getting exception that "The given path's format is not supported" . Here is my function code:

private void Copy(string letter)
{
    string sourceDir = (txtPath.ToString());
    string targetDir = letter;
    foreach (var file in Directory.GetFiles(sourceDir))
        File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)), true);
}

To refer to the content of a TextBox you use the TextBox.Text property

private void Copy(string letter)
{
    string sourceDir = txtPath.Text.Trim();
    string targetDir = letter;

    // Check if source and target exists....
    if(Directory.Exists(sourceDir) && Directory.Exists(targetDir))
    {
        foreach (var file in Directory.GetFiles(sourceDir))
            File.Copy(file, Path.Combine(targetDir, Path.GetFileName(file)), true);
    }
    else
    {
       MessageBox.Show("Source=" + sourceDir + " or Target: " + targetDir + " doesn't exist"): 
    }
}

Calling the ToString() method directly on the instance of the TextBox returns the name of the class followed by the text property (Something like "System.Windows.Forms.TextBox, Text:content of the textbox" ) and obviously this is not a valid path

It is not clear from your comments what is the content of the variable letter. So you should also be sure that the variable targetDir points to an actual valid path. (A single drive letter CD or E are not valid paths)

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