Auto incrementing saved file name

ejleiss

Active member
Joined
Oct 1, 2012
Messages
37
Programming Experience
1-3
Hello,

I am currently creating a file a the beginning of running my program using oFileStream = New System.IO.FileStream("FileName", System.IO.FileMode.Create).
Data from a serial port is being saved to this file throughout the program, and what I am looking to do is close this current file with a button and open a new file with the same "FileName" but I would like this file name to be incremented each time I click the button. Is there an easy way to accomplish this?
 
Yes, you can use a loop for the numbers, then check if a file with that number already exists with IO.File.Exists method.
An alternative is to store the last number you used in a setting and increment that by 1 next time.
 
Yes, you can use a loop for the numbers, then check if a file with that number already exists with IO.File.Exists method.
An alternative is to store the last number you used in a setting and increment that by 1 next time.


I have this code snippet working pretty well, however I would like to specify these files as .bin files. I don't quite know what the syntax of that would be to keep the original FileName and structure (ie, FileName.bin) but when it increments have the counter number within the file name (ie. FileName1.bin).

While IO.File.Exists(newFileName)
counter = counter + 1
newFileName = String.Format("{0}({1}", "C:\FileName", counter.ToString())

End While
 
Hi,

This should do the trick for you. Just change the startFileName to the file you need to check:-

VB.NET:
Imports System.IO
 
Public Class Form1
 
  Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim startFileName As String = "c:\YourFileName.txt"
    Dim endFileName As String = String.Empty
    Dim Counter As Integer = 1
 
    Do
      Dim myFileInfo As New FileInfo(startFileName)
      endFileName = myFileInfo.DirectoryName & IIf(Not myFileInfo.DirectoryName.EndsWith("\"), "\", String.Empty).ToString & Path.GetFileNameWithoutExtension(startFileName) & Counter & myFileInfo.Extension
      Counter += 1
    Loop Until Not File.Exists(endFileName)
    MsgBox("New File Name to Use Is : " & endFileName)
  End Sub
End Class


Hope that helps.

Cheers,

Ian
 
Back
Top