Not sure how Directory.CreateDirectory() works

2019-08-23 06:22发布

问题:

I have this code in my controller:

public ActionResult Upload(ScormUploadViewModel model)
{
  if (ModelState.IsValid)
  {
    if (model.ScormPackageFile != null)
    {
      string zipCurFile = model.ScormPackageFile.FileName;
      string destinationDirectoryName = Path.GetFullPath(zipCurFile);
      //.GetFileNameWithoutExtension(zipCurFile);
      Directory.CreateDirectory(destinationDirectoryName);
    }
   }
 }

I upload a zip file through my view and then need to unzip it in the same location in a folder with the same name as the zipfilename

the file is: C:\TFSPreview\Zinc\Web\Project\ScormPackages\Windows 8 Training SkyDrive - Spanish.zip

I need to create a folder in C:\TFSPreview\Zinc\Web\Project\ScormPackages\ with the name: Windows 8 Training SkyDrive - Spanish

thus have: C:\TFSPreview\Zinc\Web\Project\ScormPackages\Windows 8 Training SkyDrive - Spanish\

and UNZIP in this above folder all the files contained in C:\TFSPreview\Zinc\Web\Project\ScormPackages\Windows 8 Training SkyDrive - Spanish.zip

so my question is: will CreateDirectory() create the folder Windows 8 Training SkyDrive - Spanish in C:\TFSPreview\Zinc\Web\Project\ScormPackages\ or will it try and create the folder in just c:??

thanks

回答1:

It will create the directory inside C:\TFSPreview\Zinc\Web\Project\ScormPackages\. In fact, it will create all directories in that path if they don't already exist:

Any and all directories specified in path are created, unless they already exist or unless some part of path is invalid. The path parameter specifies a directory path, not a file path. If the directory already exists, this method does not create a new directory, but it returns a DirectoryInfo object for the existing directory.

However, this code has a bug: destinationDirectoryName is not the path to a directory, it's a path to a file inside the destination directory. So what you should be doing is

// zipCurFile = C:\...\ScormPackages\Windows 8 Training SkyDrive - Spanish.zip
// Path.GetDirectoryName gives "C:\...\ScormPackages"
// Path.GetFileName gives "Windows 8 Training SkyDrive - Spanish"
// Path.Combine on these two gives you the correct target

Directory.CreateDirectory(
    Path.Combine(
        Path.GetDirectoryName(zipCurFile), Path.GetFileName(zipCurFile));