Search code examples
c#directoryfile-copying

Error in Copying File using C#


I have a .aspx page which creates HTML file dynamically on Button click. The .html page gets created successfully but, not able to copy the created file to the destination using File.Copy method.

Code Behind:

 protected void btnPublish_Click(object sender, EventArgs e)
    {
        //copy the created file content to destination
         string sourcePath=string.Empty;
         string destiPath = @"d://test//";
        if(!string.IsNullOrEmpty(hdnPublishPath.Value))
        { 
            sourcePath= hdnPublishPath.Value;
            if (!Directory.Exists(destiPath)) // check if folde exist
            {
                Directory.CreateDirectory(destiPath); // create folder
                //Directory.Delete(destiPath, true);  // delete folder
            }

            File.Copy(sourcePath, destiPath,true);
        }
    }

It gives exception:Directory not found exception.

enter image description here

The directory gets created on mentioned drive(D:/) but the file copy fails.

NOTE: Currently the path is of "local" but later on this file will be copied to any remote server location


Solution

  • You will want to have the path and file name as your destination, not the directory:

    File.Copy(sourcePath, Path.Combine(destiPath, filename));
    

    If you supply only the target directory, you will get the exception that you get now.