creating files, recursively creating directories

2020-03-01 02:25发布

I was reading some file IO tutorials for C# and have managed to write out some files, but what if the path I'm given contains directories?

For example, I want to create the file called data/my_file except data folder doesn't exist.

The line,

BinaryWriter outFile = new BinaryWriter(File.OpenWrite(path));

where path is the above string, crashes with the message that part of the path doesn't exist, which means C# isn't creating them as required.

I would like C# to handle all of the messy directory creation and checking for me instead of me having to parse the path and create all of the necessary directories. Is this possible? Otherwise, is there a snippet of code that I can just copy over into my project which will handle anything I might be overlooking (since I don't know much about file management).

标签: c#
5条回答
▲ chillily
2楼-- · 2020-03-01 02:34

While System.IO.Directory.CreateDirectory() will indeed create directories for you recursively, I came across a situation where I had to come up with my own method. Basically System.IO doesn't support paths over 260 characters, which forced me to use Delimon.Win32.IO library, which works with long paths, but doesn't create directories recursively.

Here's the code I used for creating directories recursively:

void CreateDirectoryRecursively(string path)
{
    string[] pathParts = path.Split('\\');

    for (int i = 0; i < pathParts.Length; i++)
    {
        if (i > 0)
            pathParts[i] = Path.Combine(pathParts[i - 1], pathParts[i]);

        if (!Directory.Exists(pathParts[i]))
            Directory.CreateDirectory(pathParts[i]);
    }
}
查看更多
爷、活的狠高调
3楼-- · 2020-03-01 02:43

So, the above didn't work super well for me for basic directory creation. I modified this a bit to handle common cases for drive letters and a path with a file resource on the end.

    public bool CreateDirectoryRecursively(string path)
    {
        try
        {
            string[] pathParts = path.Split('\\');
            for (var i = 0; i < pathParts.Length; i++)
            {
                // Correct part for drive letters
                if (i == 0 && pathParts[i].Contains(":"))
                {
                    pathParts[i] = pathParts[i] + "\\";
                } // Do not try to create last part if it has a period (is probably the file name)
                else if (i == pathParts.Length-1 && pathParts[i].Contains("."))
                {
                    return true;
                }
                if (i > 0) { 
                    pathParts[i] = Path.Combine(pathParts[i - 1], pathParts[i]);
                }
                if (!Directory.Exists(pathParts[i]))
                {
                    Directory.CreateDirectory(pathParts[i]);
                }
            }
            return true;
        }
        catch (Exception ex)
        {
            var recipients = _emailErrorDefaultRecipients;
            var subject = "ERROR: Failed To Create Directories in " + this.ToString() + " path: " + path;
            var errorMessage = Error.BuildErrorMessage(ex, subject);
            Email.SendMail(recipients, subject, errorMessage);
            Console.WriteLine(errorMessage);
            return false;

        }

    }
查看更多
孤傲高冷的网名
4楼-- · 2020-03-01 02:45

System.IO.Directory.CreateDirectory() will create all directories and subdirectories in a specified path, should they not already exist.

You can call it, passing the path, to ensure the folder structure is created prior to writing your file.

查看更多
聊天终结者
5楼-- · 2020-03-01 02:50

Previous answers didn't handle Network paths. Attached code which also handles that.

/// <summary>
/// tests (and creates missing) directories in path containing many 
subDirectories which might not exist.
    /// </summary>
    /// <param name="FN"></param>
    public static string VerifyPath(string FN, out bool AllOK)
    {
        AllOK = true;
        var dir = FolderUtils.GetParent(FN);
        if (!Directory.Exists(dir))//todo - move to folderUtils.TestFullDirectory
        {
            const char DIR = '\\';
            //string dirDel = "" + DIR;

            string[] subDirs = FN.Split(DIR);
            string dir2Check = "";
            int startFrom = 1;//skip "c:\"
            FN = CleanPathFromDoubleSlashes(FN);
            if (FN.StartsWith("" + DIR + DIR))//netPath
                startFrom = 3;//FN.IndexOf(DIR, 2);//skip first two slashes..
            for (int i = 0; i < startFrom; i++)
                dir2Check += subDirs[i] + DIR;//fill in begining

            for (int i = startFrom; i < subDirs.Length - 1; i++)//-1 for the file name..
            {
                dir2Check += subDirs[i] + DIR;
                if (!Directory.Exists(dir2Check))
                    try
                    {
                        Directory.CreateDirectory(dir2Check);
                    }
                    catch { AllOK = false; }
            }
        }
        if (File.Exists(FN))
            FN = FolderUtils.getFirstNonExistingPath(FN);
        if (FN.EndsWith("\\") && !Directory.Exists(FN))
            try { Directory.CreateDirectory(FN); }
            catch
            {
                HLogger.HandleMesssage("couldn't create dir:" + FN, TypeOfExceptions.error, PartsOfSW.FileStructure);
                AllOK = false;
            }

        return FN;

    }

And the "CleanDoubleSlashes function":

  public static string CleanPathFromDoubleSlashes(string basePath)
    {
        if (string.IsNullOrEmpty(basePath) || basePath.Length < 2)//don't clean first \\ of LAN address
            return basePath;
        for (int i = basePath.Length - 1; i > 1; i--)
        {
            if ((basePath[i] == '\\' && basePath[i - 1] == '\\') || (basePath[i] == '/' && basePath[i - 1] == '/'))
            {
                basePath = basePath.Remove(i, 1);//Substring(0, i - 2) + basePath.Substring(i, basePath.Length - 1 - i);
            }
        }
        return basePath;
    }
查看更多
劫难
6楼-- · 2020-03-01 02:58

here is how I usually do it

Directory.CreateDirectory(Path.GetDirectoryName(filePath));

^ this should take care of ensuring all necessary folders (regardless if some of them already exist) that precedes your file are created. E.g. if you pass it "c:/a/b/c/data/my file.txt", it should ensure "c:/a/b/c/data" path is created.

查看更多
登录 后发表回答