Hi Alls,

I need help regarding to rename my event file by current date. It's mean my file will be rename by date automaticly.....i can write to the text but the name not replace with the current date....can u help me...plz

Here's a Q&D solution

Public Function NewFileName(ByVal FileName As String, ByVal FileExt As String) As String
  '
  Dim NewName As String
  Dim DateStr As String
  Dim TempStr() As String
  Dim i As Integer

  ' Get date and time
  DateStr = System.DateTime.Now.ToString

  ' Remove time
  TempStr = Split(DateStr, " ")
  DateStr = TempStr(0) ' Date part only

  ' Append
  If String.IsNullOrEmpty(FileName) Then
    NewName = DateStr
  Else
    NewName = FileName & DateStr
  End If

  ' Remove illegal characters
  For i = 0 To Path.GetInvalidFileNameChars.GetUpperBound(0)
    If NewName.IndexOf(Path.GetInvalidFileNameChars(i)) >= 0 Then
      ' Remove illegal character
      NewName.Replace(Path.GetInvalidFileNameChars(i), "")
    End If
  Next i

  ' Add file extension
  If Not String.IsNullOrEmpty(FileExt) Then
    NewName = NewName & "." & FileExt
  End If

  Return NewName

End Function

Call it: FileName = NewFileName("MyLog", "") or FileName = NewFileName("MyLog", "log")

String.IsNullOrEmpty() comes with .NET 2.0 or later so you're obviously using some .NET 1.x version.

I fixed the code to be compatible with .NET 1.x, at least for String.IsNullOrEmpty() part. I just commented out two lines of the original code in the case you will some day use .NET 2.0 or later

Public Function NewFileName(ByVal FileName As String, ByVal FileExt As String) As String
  '
  Dim NewName As String
  Dim DateStr As String
  Dim TempStr() As String
  Dim i As Integer

  ' Get date and time
  DateStr = System.DateTime.Now.ToString

  ' Remove time
  TempStr = Split(DateStr, " ")
  DateStr = TempStr(0) ' Date part only

  ' .NET 1.x compatibility replacement for String.IsNullOrEmpty()
  If FileName Is Nothing Then
    FileName = ""
  End If
  If FileExt Is Nothing Then
    FileExt = ""
  End If

  ' Append
  
  'If String.IsNullOrEmpty(FileName) Then
  If FileName.Length = 0 Then
    NewName = DateStr
  Else
    NewName = FileName & DateStr
  End If

  ' Remove illegal characters
  For i = 0 To Path.GetInvalidFileNameChars.GetUpperBound(0)
    If NewName.IndexOf(Path.GetInvalidFileNameChars(i)) >= 0 Then
      ' Remove illegal character
      NewName.Replace(Path.GetInvalidFileNameChars(i), "")
    End If
  Next i

  ' Add file extension
  'If Not String.IsNullOrEmpty(FileExt) Then
  If FileExt.Length > 0 Then
    NewName = NewName & "." & FileExt
  End If

  Return NewName

End Function
This article has been dead for over six months. Start a new discussion instead.