Home > database >  How can I get part of folder path name without the child?
How can I get part of folder path name without the child?

Time:10-29

I check if directories exist if not create them :

if (textBoxRadarPath.Text != "")
{
    if (!Directory.Exists(textBoxRadarPath.Text))
    {
        Directory.CreateDirectory(textBoxRadarPath.Text);
    
        btnStart.Enabled = true;
    }
}
    
if (textBoxSatellitePath.Text != "")
{
    if (!Directory.Exists(textBoxSatellitePath.Text))
    {
        Directory.CreateDirectory(textBoxSatellitePath.Text);
    
        btnStart.Enabled = true;
    }
}

For example the textBoxRadarOath.Text content is :

 D:\Downloaded Images\Radar

I want to get only the part D:\Downloaded Images and in this path to create a new one name Animated Gifs

Animated Gifs directory should be placed under D:\Downloaded Images

I can get the last name of the path Radar but I want to get the name without the child Radar or even if there were more childs like D:\Downloaded Images\Radar\1\2\3\4\5 still I want to get only D:\Downloaded Images and create a directory under D:\Downloaded Images

CodePudding user response:

If you want to manipulate with folders, you can try using DirectoryInfo class:

using System.IO;

...

// D:\Downloaded Images\Radar\1\2\3\4\5
DirectoryInfo dir = new DirectoryInfo(textBoxRadarOath.Text);

// Going down up to "D:\Downloaded Images\Radar"
while (!string.Equals(dir.Name, "Radar", StringComparison.OrdinalIgnoreCase))
  dir = dir.Parent;

// Drop "Radar" and Add "Animated Gifs"
dir = new DirectoryInfo(Path.Combine(dir.Parent.FullName, "Animated Gifs"));

If you want to check if Animated Gifs folder exists:

// D:\Downloaded Images\Radar\1\2\3\4\5
DirectoryInfo dir = new DirectoryInfo(textBoxRadarOath.Text);

while (!string.Equals(dir.Name, "Radar", StringComparison.OrdinalIgnoreCase))
  dir = dir.Parent;

dir = new DirectoryInfo(Path.Combine(dir.Parent.FullName, "Animated Gifs"));

if (!dir.Exists) {
  dir.Create();

  btnStart.Enabled = true;
}
  • Related