TransWikia.com

Removing part of DirectoryName

Stack Overflow Asked on November 12, 2021

I’m trying to remove part of a path in a string but it doesn’t actually remove anything. I’m not sure what I’m doing wrong in this method.

string path = AppDomain.CurrentDomain.BaseDirectory + "/FastDL-Generator-Input/";
DirectoryInfo d = new DirectoryInfo(path + "materials/");
FileInfo[] Files = d.GetFiles("*.*", SearchOption.AllDirectories);

foreach (FileInfo file in Files)
{                
    string filePath = file.DirectoryName.Replace(path, "");
    status3.Text = filePath;
}

It doesn’t run with any errors, but it’s not removing anything. This is the output

"C:Users*****sourcereposFastDL GeneratorFastDL GeneratorbinDebugFastDL-Generator-Inputmaterialstest"

It should be printing

"materialstest" 

instead. If you can provide any advice, I would greatly appreciate it.

2 Answers

You need to change these two lines:

string path = AppDomain.CurrentDomain.BaseDirectory + "/FastDL-Generator-Input/";
DirectoryInfo d = new DirectoryInfo(path + "materials/");

To this:

string path = AppDomain.CurrentDomain.BaseDirectory + "FastDL-Generator-Input\";
DirectoryInfo d = new DirectoryInfo(path + "materials\");

Note the change in direction of the slashes in the path.

Answered by Kev Ritchie on November 12, 2021

You're using a forward slash in your path, I ran your code on my machine using back slash and it worked as you expected.

Try this:

    string path = AppDomain.CurrentDomain.BaseDirectory + "FastDL-Generator-Input\";
    DirectoryInfo d = new DirectoryInfo(path + "materials\");
    FileInfo[] Files = d.GetFiles("*.*", SearchOption.AllDirectories);

    foreach (FileInfo file in Files)
    {
        string filePath = file.DirectoryName.Replace(path, "");
        status3.Text = filePath;
    }

Answered by Mikael on November 12, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP