Bentley Pascoe
Bentley Pascoe

Reputation: 1

How do I remove a portion of a line of text in C#

I need some assistance removing a portion of a line of text from a file. Example:

let's say I have output from a dir listing like so:

 Directory of C:\Data\Junk

03/12/2014  08:35 AM    <DIR>          .
03/12/2014  08:35 AM    <DIR>          ..
03/05/2014  05:36 PM               397 junk.xml
03/05/2014  05:36 PM               397 more_junk.xml

and my goal is to turn it into the following:

 Directory of C:\Data\Junk

.
..
junk.xml
more_junk.xml

I know how to do this using editors if I have an expected string to remove, but am unable to figure out how to do this dynamically. Alternatively - is there a way to detect that if the first portion of the line is a date, to then remove X characters (where X in this case would take me to the start of the file names)?

Thanks in advance for any help here!

Upvotes: 0

Views: 146

Answers (2)

VladL
VladL

Reputation: 13033

Why not just list all files using Directory.GetFiles ?

string[] files = Directory.GetFiles(@"C:\Data\Junk", "*.*", SearchOption.TopDirectoryOnly);

and then just format it as you wish, for example

Console.WriteLine(".");
Console.WriteLine("..");
foreach(string f in files)
{
  Console.WriteLine(file);
}

Upvotes: 3

UtopiaLtd
UtopiaLtd

Reputation: 2590

If you know the length of how much of the string you want to discard (which above appears to be 40 characters), you can do

yourString.Substring(40)

to get the remainder of the line.

However, the advice of the comments is sound--you probably shouldn't need to process this particular case of strings in the first place.

Upvotes: 2

Related Questions