I want those text files(log files) in a folder that is created today that has name as something20130416 and which has the word error only in the last 5 lines of it. Then attach these files and send to an email address. Am completely new to VB. I don't know how to put those files in an array or something and then attach them to mail. So far my code is:

Class Program
    Public Shared Sub Main(ByVal args As String())

        Dim log_files() As String = Directory.GetFiles("C\~", DateTime.Today.ToString("*yyyyMMdd") & ".log")

        For Each filesfound As String In log_files

            Dim contents = IO.File.ReadAllLines(filesfound)

            For counter As Integer = contents.Length - 1 To 5 Step -1

                If contents.Contains("error") Then   
                'Not sure what to do here
                    Email()
                End If

            Next

        Next
    End Sub

    Public Shared Sub Email()
        Dim m As New MailMessage()
        Dim attach = New Attachment("...")
        Dim sc As New SmtpClient()
        Try
            m.From = New MailAddress("example@gmail.com", "User")
            m.To.Add(New MailAddress("example@gmail.com", "User"))
            m.CC.Add(New MailAddress("example@gmail.com", "User"))
            m.Attachments.Add(attach)

            m.Subject = "Test1"
            m.IsBodyHtml = True
            m.Body = " These text files contains an error"
        Catch e As Exception
            MessageBox.Show(e.Message)
        End Try
    End Sub
 End Class

Dani AI

Generated

A few clarifications and a compact, reliable approach for 's scenario.

Interpretation: either you want files whose filename contains today's date (e.g. somethingYYYYMMDD.log) or files that live inside a folder whose name contains the date. The solution below shows how to find files by filename pattern; if you instead need to locate a folder first, use Directory.GetDirectories(root, "" & DateTime.Today.ToString("yyyyMMdd") & "") and then search that folder.

Key points and approach:

  • Build a filename pattern with DateTime.Today.ToString("yyyyMMdd") and use Directory.EnumerateFiles to avoid loading everything into memory.
  • Read each file line-by-line with a StreamReader opened using FileShare.ReadWrite (avoids exceptions if the logger is still writing).
  • Maintain a fixed-size queue of the last 5 lines and, while streaming, detect any earlier occurrences of the word "error". That way a file is selected only if there are no "error" occurrences before the last five lines and at least one match inside the last five lines.
  • Collect matching files, then create one MailMessage, add attachments, and send once (don’t call send inside the per-file loop). Dispose MailMessage/SmtpClient with Using blocks.

Example (VB.NET — adapt paths/SMTP settings):

Imports System.IO
Imports System.Net
Imports System.Net.Mail
Imports System.Text.RegularExpressions
Imports System.Linq

Dim rootPath = "C:\Logs"
Dim pattern = "*" & DateTime.Today.ToString("yyyyMMdd") & "*.log"
Dim rx = New Regex("\berror\b", RegexOptions.IgnoreCase)
Dim candidates As New List(Of String)()

For Each f In Directory.EnumerateFiles(rootPath, pattern, SearchOption.TopDirectoryOnly)
    Dim tail As New Queue(Of String)()
    Dim hasEarlierError As Boolean = False

    Using fs = File.Open(f, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)
        Using sr = New StreamReader(fs)
            While Not sr.EndOfStream
                Dim line = sr.ReadLine()
                If tail.Count = 5 Then
                    If rx.IsMatch(tail.Dequeue()) Then hasEarlierError = True
                End If
                tail.Enqueue(line)
            End While
        End Using
    End Using

    If Not hasEarlierError AndAlso tail.Any(Function(l) rx.IsMatch(l)) Then
        candidates.Add(f)
    End If
Next

If candidates.Any() Then
    Using msg As New MailMessage()
        msg.From = New MailAddress("from@example.com")
        msg.To.Add("to@example.com")
        msg.Subject = "Logs with errors in last 5 lines"
        For Each f In candidates
            msg.Attachments.Add(New Attachment(f))
        Next
        Using smtp As New SmtpClient("smtp.server.com", 587)
            smtp.EnableSsl = True
            smtp.Credentials = New NetworkCredential("user", "pass")
            smtp.Send(msg)
        End Using
    End Using
End If

Notes and troubleshooting:

  • Your original code checked the whole array with Contains and invoked Email() inside the loop; that will not correctly test only the last 5 lines and will send many emails. Collect matches and send once.
  • Use regex with word boundaries for whole-word matching and Index/Comparison or Regex for case-insensitive matching.
  • Watch file permissions, locks, and attachment-size limits (compress or upload if files are large). Dispose MailMessage/SmtpClient to release file locks.

Sorry the code got posted twice. Its from class Program to end class.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.