Blake
Blake

Reputation: 33

Removing part of DirectoryName

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\*****\source\repos\FastDL Generator\FastDL Generator\bin\Debug\FastDL-Generator-Input\materials\test"

It should be printing

"materials\test" 

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

Upvotes: 0

Views: 106

Answers (2)

Kev Ritchie
Kev Ritchie

Reputation: 1647

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.

Upvotes: 0

Mikael
Mikael

Reputation: 982

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

Upvotes: 1

Related Questions