Solved

Find A File With A Dynamic Name In VB.NET

Posted on 2011-03-21
10
305 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 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
Stressed Out?

Watch some penguins on the livecam!

 
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 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

Did you know SD-WANs can improve network connectivity? Check out this webinar to learn how an SD-WAN simplified, one-click tool can help you migrate and manage data in the cloud.

Question has a verified solution.

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

A basic question.. “What is the Garbage Collector?” The usual answer given back: “Garbage collector is a background thread run by the CLR for freeing up the memory space used by the objects which are no longer used by the program.” I wondered …
This document covers how to connect to SQL Server and browse its contents.  It is meant for those new to Visual Studio and/or working with Microsoft SQL Server.  It is not a guide to building SQL Server database connections in your code.  This is mo…
Come and listen to Percona CEO Peter Zaitsev discuss what’s new in Percona open source software, including Percona Server for MySQL (https://www.percona.com/software/mysql-database/percona-server) and MongoDB (https://www.percona.com/software/mongo-…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…

724 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