Solved

Find A File With A Dynamic Name In VB.NET

Posted on 2011-03-21
10
300 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
 
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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

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

What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
asp.net mvc5 3 38
How Can I fix my MouseHover Event? 14 28
Setting location of a form 4 22
Limiting string to two deciamls 18 36
Summary Displaying images in RichTextBox is a common requirement with limited solutions available. Pasting through clipboard or embedding into RTF content only support static images.  This article describes how to insert Windows control objects int…
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…
Polish reports in Access so they look terrific. Take yourself to another level. Equations, Back Color, Alternate Back Color. Write easy VBA Code. Tighten space to use less pages. Launch report from a menu, considering criteria only when it is filled…
This tutorial demonstrates a quick way of adding group price to multiple Magento products.

744 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

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now