Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Find A File With A Dynamic Name In VB.NET

Posted on 2011-03-21
10
Medium Priority
?
308 Views
Last Modified: 2013-12-17
I have a text file which part of the name will change on a daily basis.  
dlylicex-03112011-1401.txt
The file is located in the same directory as the application.
I already have a brilliant piece of code written by Idle_Mind that will parse the file once I find it.  I need to know how to find the a file based on part of the file name then rename it after it is processed.
Sub ParseMe()
        ' pass data to array, rearrange
        Dim Path As String = strCurrentDir
        Dim DataFile As String = strFileName
        Dim V_File As String = strFileNameNew
        Dim strLicensePlate As String
        Dim intLicensePlateLength As Integer
        Dim intFixedWidthLength As Integer = 11
        Dim intPlateAndWhiteSpaceLength As Integer
        Using sw_V As New StreamWriter(System.IO.Path.Combine(Path, V_File), False)
            Using sr As New StreamReader(System.IO.Path.Combine(Path, DataFile))
                While Not sr.EndOfStream
                    Dim values As New List(Of String)
                    values.AddRange(sr.ReadLine.Split(";")) 'find semicolon and make column
                    If values(0).ToUpper = "ST" Or values(0).ToUpper = "SV" Then
                        'if first column is "ST" or "SV", then
                        '   move column 10 to index 0 and add fixed-width white space of 11 characters. 
                        '   replace all semicolons with a single white space
                        strLicensePlate = values(10)                                                ' set plate characters into string var
                        intLicensePlateLength = Len(strLicensePlate)                                ' find length of string (number of characters)
                        intPlateAndWhiteSpaceLength = intFixedWidthLength - intLicensePlateLength   ' find fixed-width length
                        'MessageBox.Show(intRemainLength)
                        values.Insert(0, values(10) & Space(intPlateAndWhiteSpaceLength))           ' rearrange columns with fixed-width white space
                        values.RemoveAt(11)                                                         ' remove unwanted column
                        Dim output As String = String.Join(" ", values.ToArray)                     ' add to array
                        sw_V.WriteLine(output)                                                      ' write to file
                    End If
                End While
            End Using
        End Using
    End Sub

Open in new window

0
Comment
Question by:asc2010
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
10 Comments
 
LVL 36

Assisted Solution

by:Miguel Oz
Miguel Oz earned 1000 total points
ID: 35185068
Code to find files:
           DirectoryInfo dir = new DirectoryInfo(Environment.CurrentDirectory);
            FileInfo[] xmlFiles = dir.GetFiles("*.xml", SearchOption.TopDirectoryOnly);
            if (xmlFiles != null && xmlFiles.Length > 0)
            {
                foreach (FileInfo xmlFile in xmlFiles)
                {
                     //Do your custom code here
                }
            }
Note: Change "*.xml" to whatever you need e.g "dlylicex-*.txt"

To rename use the File.Move method:
http://msdn.microsoft.com/en-us/library/system.io.file.move.aspx


0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 35185091
Hi again asc2010,

Is the "dlylicex" part of the file constant?  You have to let us know which parts stay the same and which parts change so we can help you find the dynamic filename!  =)
0
 

Author Comment

by:asc2010
ID: 35186143
Hi there Idle_Mind!!  Yes, the "dlycilex" is constant.  Sorry about that!
0
NFR key for Veeam Agent for Linux

Veeam is happy to provide a free NFR license for one year.  It allows for the non‑production use and valid for five workstations and two servers. Veeam Agent for Linux is a simple backup tool for your Linux installations, both on‑premises and in the public cloud.

 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 35186316
mas_oz2003 pretty much gave you a working solution then.  Do you need help converting that to VB.Net?
0
 

Author Comment

by:asc2010
ID: 35190386
Idle_Mind, your help is always appreciated.  Should I ask for your help converting this to VB.NET in a separate question?
0
 

Author Comment

by:asc2010
ID: 35190448
I also need to be able to differentiate between older files and the most recent file based on the file name.  
0
 
LVL 86

Expert Comment

by:Mike Tomlinson
ID: 35190483
We can help you here no problem.

So there will be multiple files in the folder and you need just the newest one based on the date contained within the NAME itself?
0
 

Author Comment

by:asc2010
ID: 35190512
There should only be a single file with this file name in the directory.  However, in the event that the program does not run and multiple files exist, I need to use only the most current.
0
 
LVL 86

Accepted Solution

by:
Mike Tomlinson earned 1000 total points
ID: 35191960
Here is how to sort the filenames and find the newest one based on the value in the NAME:
Imports System.IO
Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        ' Example FileName: dlylicex-03112011-1401.txt

        Dim filter As String = "dlylicex*.txt"
        Dim folder As String = "C:\Users\Mike\Documents\TestFolder"

        Dim di As New System.IO.DirectoryInfo(folder)
        Dim matches As New List(Of FileInfo)
        matches.AddRange(di.GetFiles(filter))
        If matches.Count > 0 Then
            matches.Sort(AddressOf CompareFileNames)
            Dim NewestFile As String = matches(0).FullName

            ' ... use "NewestFile" somehow ...
            MessageBox.Show(NewestFile, "Newest File", MessageBoxButtons.OK, MessageBoxIcon.Information)

        End If
    End Sub

    Private Function CompareFileNames(ByVal fiA As FileInfo, ByVal fiB As FileInfo) As Integer
        Dim comparison As Integer = comparison = fiB.Name.CompareTo(fiA.Name) ' default comparison

        Dim valuesA() As String = fiA.Name.Split("-")
        Dim valuesB() As String = fiB.Name.Split("-")
        If valuesA.Length = 3 AndAlso valuesB.Length = 3 Then
            Dim DateA, DateB As DateTime
            Dim dateFormat As String = "MMddyyyy"

            Dim strDateA As String = valuesA(1)
            Dim strDateB As String = valuesB(1)
            If DateTime.TryParseExact(strDateA, dateFormat, Nothing, Globalization.DateTimeStyles.None, DateA) AndAlso _
                DateTime.TryParseExact(strDateB, dateFormat, Nothing, Globalization.DateTimeStyles.None, DateB) Then

                comparison = DateB.CompareTo(DateA)

            End If
        End If

        Return comparison
    End Function

End Class

Open in new window

0
 

Author Comment

by:asc2010
ID: 35192947
Idle_Mind,

Thanks again for your help!! You are a genius!!
0

Featured Post

NFR key for Veeam Backup for Microsoft Office 365

Veeam is happy to provide a free NFR license (for 1 year, up to 10 users). This license allows for the non‑production use of Veeam Backup for Microsoft Office 365 in your home lab without any feature limitations.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
This tutorial will teach you the special effect of super speed similar to the fictional character Wally West aka "The Flash" After Shake : http://www.videocopilot.net/presets/after_shake/ All lightning effects with instructions : http://www.mediaf…
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…

604 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question