crystalnoob
crystalnoob

Reputation: 27

Find and copy the latest file

Our program is going to save PDFs to a network folder. I will then be copying the PDFs to a web server. There becomes a problem when a user saves/archives the same report more than once.

Example:

Is there a way I could copy the latest version? I only want DAGH4 (002).PDF and DANYL (001).PDF to be copied. Or is there a way to rename and save the latest version?

Another thought

Using this code I check if the file exists and allow the user to click an thumbnail to open the associated PDF.

Dim pdf_path = Server.MapPath(String.Format("../Reports/{0}.pdf",     
SerialNumber))
lblSerial.Visible = System.IO.File.Exists(pdf_path)
HyperLinkSerial.Visible = System.IO.File.Exists(pdf_path)
HyperLinkSerial.Text = "Inspection"
HyperLinkSerial.NavigateUrl = "../Reports/" & SerialNumber & ".PDF"

However, I need to only find and show the DAGH4 (002).PDF with the modified date 3/16/2016 10:10 AM

Is that possible using VB .NET?

Upvotes: 0

Views: 471

Answers (1)

Mark
Mark

Reputation: 8150

To find the latest copy of each file, you could use LINQ to group by serial number, sort by modification date, and select the first item for each group. Note that this assumes that your "SerialNumber" is just letters and numbers (what the regex matches):

Dim latest As IEnumerable(Of String) =
    From f In New DirectoryInfo(Server.MapPath("../Reports")).EnumerateFiles("*.PDF")
    Let serialNumber = Regex.Match(f.Name, "^\w+").Value
    Order By serialNumber Ascending, f.LastWriteTime Descending
    Group By serialNumber Into Group
    Select Group.First().f.FullName

latest will have the full path/name for the latest (based on modification date) file for each serial number.

Upvotes: 1

Related Questions