检查目录中是否存在文件夹,并使用C#创build它们

如何检查目录C:/包含名为MP_Upload的文件夹,如果不存在,请自动创build文件夹?

我正在使用Visual Studio 2005 C#。

这应该有所帮助:

 using System.IO; ... string path = @"C:\MP_Upload"; if(!Directory.Exists(path)) { Directory.CreateDirectory(path); } 
 using System.IO; ... Directory.CreateDirectory(@"C:\MP_Upload"); 

Directory.CreateDirectory正是你想要的:它创build目录,如果它不存在。 没有必要先做一个明确的检查。

path中指定的任何和所有目录都将被创build,除非它们已经存在,或者path的某些部分无效。 path参数指定目录path,而不是文件path。 如果目录已经存在,这个方法什么都不做。

(这也意味着如果需要,path中的所有目录都会被创build: CreateDirectory(@"C:\a\b\c\d")就足够了,即使C:\a还不存在。


让我添加一个谨慎的关于你的目录select的话,但是:直接在系统分区根目录下创build一个文件夹C:\是皱眉。 考虑让用户select一个文件夹或在%APPDATA%%LOCALAPPDATA%创build一个文件夹(使用Environment.GetFolderPath )。 Environment.SpecialFolder枚举的MSDN页面包含特殊操作系统文件夹及其用途的列表。

 if(!System.IO.Directory.Exists(@"c:\mp_upload")) { System.IO.Directory.CreateDirectory(@"c:\mp_upload"); } 

这应该工作

 if(!Directory.Exists(@"C:\MP_Upload")) { Directory.CreateDirectory(@"C:\MP_Upload"); } 
 using System; using System.IO; using System.Windows.Forms; namespace DirCombination { public partial class DirCombination : Form { private const string _Path = @"D:/folder1/foler2/folfer3/folder4/file.txt"; private string _finalPath = null; private string _error = null; public DirCombination() { InitializeComponent(); if (!FSParse(_Path)) Console.WriteLine(_error); else Console.WriteLine(_finalPath); } private bool FSParse(string path) { try { string[] Splited = path.Replace(@"//", @"/").Replace(@"\\", @"/").Replace(@"\", "/").Split(':'); string NewPath = Splited[0] + ":"; if (Directory.Exists(NewPath)) { string[] Paths = Splited[1].Substring(1).Split('/'); for (int i = 0; i < Paths.Length - 1; i++) { NewPath += "/"; if (!string.IsNullOrEmpty(Paths[i])) { NewPath += Paths[i]; if (!Directory.Exists(NewPath)) Directory.CreateDirectory(NewPath); } } if (!string.IsNullOrEmpty(Paths[Paths.Length - 1])) { NewPath += "/" + Paths[Paths.Length - 1]; if (!File.Exists(NewPath)) File.Create(NewPath); } _finalPath = NewPath; return true; } else { _error = "Drive is not exists!"; return false; } } catch (Exception ex) { _error = ex.Message; return false; } } } } 
  String path = Server.MapPath("~/MP_Upload/"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); }