Solved

Find A File With A Dynamic Name In VB.NET

Posted on 2011-03-21
10
303 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
  • 5
  • 4
10 Comments
 
LVL 35

Assisted Solution

by:Miguel Oz
Miguel Oz earned 250 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 85

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
Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

 
LVL 85

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 85

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 85

Accepted Solution

by:
Mike Tomlinson earned 250 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

Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

Question has a verified solution.

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

Recently while returning home from work my wife (another .NET developer) was murmuring something. On further poking she said that she has been assigned a task where she has to serialize and deserialize objects and she is afraid of serialization. Wha…
In my previous two articles we discussed Binary Serialization (http://www.experts-exchange.com/A_4362.html) and XML Serialization (http://www.experts-exchange.com/A_4425.html). In this article we will try to know more about SOAP (Simple Object Acces…
Microsoft Active Directory, the widely used IT infrastructure, is known for its high risk of credential theft. The best way to test your Active Directory’s vulnerabilities to pass-the-ticket, pass-the-hash, privilege escalation, and malware attacks …

825 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