Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Is there a better way to get part of a string?

Status
Not open for further replies.

djj55

Programmer
Feb 6, 2006
1,761
US
Hello, VB.NET 2010
I am self taught at VB.NET and have not worked with it for a couple of years. I have code that works fine but I would like to know if there is a better way.
Code:
Dim sfFiles As New IO.DirectoryInfo("mypath")
Dim sfFileList As IO.FileInfo() = sfFiles.GetFiles(".txt")
Dim sfFileInfo As IO.FileInfo
Dim farray As New List(Of String)
Dim ACounter As Int16 ' counter used to get last file
Dim InputFile AS String

For Each sfFileInfo In sfFileList
    farray.Add(sfFileInfo.CreationTime.ToString("u") & "|" & sfFileInfo.Name)
Next
farray.Sort()
ACounter = farray.Count - 1

InputFile = [COLOR=red]farray(ACounter).ToString.Substring(farray(ACounter).ToString.IndexOf("|") + 1, 12)[/color]
What I want is the most resently dated file. I am puting the date and filename into a list in order to sort it. I then look at the last array element and by finding the pipe I can then get the filename.
As I say this works (for both LIST and ARRAYLIST) but I am trying to see if the code in red can be modified. Is there a better way?

djj
The Lord is my shepherd (Psalm 23) - I need someone to lead me!
 

This code will get the most recent file from a directory:

Code:
Dim di As DirectoryInfo = New DirectoryInfo("Path\to\directory")

Dim fi As FileInfo = di.GetFiles().OrderByDescending(Function(f) f.LastWriteTime).First()

MsgBox(fi.Name)

I used to rock and roll every night and party every day. Then it was every other day. Now I'm lucky if I can find 30 minutes a week in which to get funky. - Homer Simpson

Arrrr, mateys! Ye needs ta be preparin' yerselves fer Talk Like a Pirate Day!
 
Thank you. That is quite a bit better and works great. I even understand what it is doing.[bigsmile]

djj
The Lord is my shepherd (Psalm 23) - I need someone to lead me!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top