Solved

Find A File With A Dynamic Name In VB.NET

Posted on 2011-03-21
10
304 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 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
Forrester Webinar: xMatters Delivers 261% ROI

Guest speaker Dean Davison, Forrester Principal Consultant, explains how a Fortune 500 communication company using xMatters found these results: Achieved a 261% ROI, Experienced $753,280 in net present value benefits over 3 years and Reduced MTTR by 91% for tier 1 incidents.

 
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

On Demand Webinar - Networking for the Cloud Era

This webinar discusses:
-Common barriers companies experience when moving to the cloud
-How SD-WAN changes the way we look at networks
-Best practices customers should employ moving forward with cloud migration
-What happens behind the scenes of SteelConnect’s one-click button

Question has a verified solution.

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

Flash (http://en.wikipedia.org/wiki/Adobe_Flash) has evolved over the years to where it has become a masterful tool for displaying content screen.  It has excellent layout placement, UI precision as well as rendering capabilities. This, along with t…
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 a recent question (https://www.experts-exchange.com/questions/29004105/Run-AutoHotkey-script-directly-from-Notepad.html) here at Experts Exchange, a member asked how to run an AutoHotkey script (.AHK) directly from Notepad++ (aka NPP). This video…

749 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