检查C#中目录是否存在并创建它们

131

如何检查目录 C:/ 中是否存在名为 MP_Upload 的文件夹,如果不存在则自动创建该文件夹?

我正在使用 Visual Studio 2005 C#。

6个回答

268

这应该会有所帮助:

using System.IO;
...

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

187
using System.IO;
...

Directory.CreateDirectory(@"C:\MP_Upload");

Directory.CreateDirectory方法恰好能够满足您的需求:如果目录不存在,则会创建该目录。无需先进行明确的检查。

除非路径中的某些部分无效或路径中指定的所有目录已经存在,否则将创建指定路径中的所有目录。路径参数指定目录路径,而非文件路径。如果目录已经存在,则此方法不执行任何操作。

(这也意味着所有沿着路径的目录都将被创建,例如CreateDirectory(@"C:\a\b\c\d")就足够了,即使C:\a尚不存在。)


但是我要对您选择的目录位置提出警告:直接在系统分区根目录C:\下创建文件夹是不被建议的。考虑让用户选择一个文件夹或在%APPDATA%%LOCALAPPDATA%中创建文件夹(可以使用Environment.GetFolderPath方法获取)。Environment.SpecialFolder枚举的MSDN页面包含了一份操作系统特殊文件夹及其用途的列表。


13
这在其他几个讨论串中已经出现过。虽然你不需要进行检查,但它确实可以使代码的意图更清晰,提高外部人员的可读性。因此保留这个检查可能是件好事。 - Matt J.
9
在这种情况下,我宁愿添加一个简短的注释而不是一个无用的函数调用。我同意这种行为并不明显,但另一方面,如果将其更恰当地命名为“EnsureDirectoryExists”,则会使该方法更难查找。 - Heinzi
5
注意事项:如果文件夹名称与现有的文件名相匹配,Directory.CreateDirectory 将会抛出异常。 - Reza M.

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

7

这应该可以正常工作。

if(!Directory.Exists(@"C:\MP_Upload")) {
    Directory.CreateDirectory(@"C:\MP_Upload");
}

2
    String path = Server.MapPath("~/MP_Upload/");
    if (!Directory.Exists(path))
    {
        Directory.CreateDirectory(path);
    }

1
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;
            }
        }
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接