如何检查目录 C:/是否包含名为 MP_Upload的文件夹,如果不存在,则自动创建该文件夹?
C:/
MP_Upload
我使用的是 VisualStudio2005C # 。
这应该会有所帮助:
using System.IO; ... string path = @"C:\MP_Upload"; if(!Directory.Exists(path)) { Directory.CreateDirectory(path); }
if(!System.IO.Directory.Exists(@"c:\mp_upload")) { System.IO.Directory.CreateDirectory(@"c:\mp_upload"); }
using System.IO; ... Directory.CreateDirectory(@"C:\MP_Upload");
Directory.CreateDirectory does exactly what you want: It creates the directory if it does not exist yet. There's no need to do an explicit check first.
路径中指定的所有目录都将被创建,除非它们已经存在或者路径的某些部分无效。Path 参数指定目录路径,而不是文件路径。如果目录已经存在,则此方法不执行任何操作。
(这也意味着所有目录 沿着小路都是在需要时创建的: 即使 C:\a还不存在,CreateDirectory(@"C:\a\b\c\d")也足够了。)
C:\a
CreateDirectory(@"C:\a\b\c\d")
但是,让我对您的目录选择添加一句警告: 不赞成在系统分区根目录 C:\的正下方创建一个文件夹。考虑让用户选择一个文件夹,或者在 %APPDATA%或 %LOCALAPPDATA%中创建一个文件夹(使用 环境)。环境,特殊文件夹枚举的 MSDN 页包含特殊操作系统文件夹的列表及其用途。
C:\
%APPDATA%
%LOCALAPPDATA%
这个应该可以
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); }