How not to overwrite files in VB.net - vb.net

I want to check if the current file exists at the same time save video to different file but it only overwrites to an existing file.
Here is my code:
Private Sub ButtonVIDEO_Click(ByVal sender As System.Object, e As System.EventArgs) Handles ButtonVIDEO.Click
f = New Filters
cap = New Capture(f.VideoInputDevices(0), f.AudioInputDevices(0))
cap.PreviewWindow = PictureBox1
Dim Filename As String = "c:\\folder\MyFile"
Dim i As Integer = 0
Dim extension As String = ".mp4"
If ButtonVIDEO.BackColor = Color.Black Then
cap.Filename = Filename + extension
If File.Exists(Filename) Then
Do
i = i + 1
Loop While File.Exists(Filename + i.ToString() + extension)
Filename = Filename + i.ToString()
End If
cap.Cue()
cap.Start()
ButtonVIDEO.BackColor = Color.Red
ButtonVIDEO.Text = "PLAYING"
ButtonPHOTO.Hide()
End If
End Sub

You are assigning the file name to cap before searching for an unsused file name.
Also, there is an error in your logic, as you are creating the full file name with Filename + i.ToString() + extension but you also append i to Filename itself with Filename = Filename + i.ToString().
So, in then end, you are appending the number twice.
Private Sub ButtonVIDEO_Click(ByVal sender As System.Object, e As System.EventArgs) _
Handles ButtonVIDEO.Click
Dim Filename As String = "c:\folder\MyFile"
Dim i As Integer = 0
Dim extension As String = ".mp4"
Dim path As String = Filename & extension
f = New Filters
cap = New Capture(f.VideoInputDevices(0), f.AudioInputDevices(0))
cap.PreviewWindow = PictureBox1
If ButtonVIDEO.BackColor = Color.Black Then
If File.Exists(path) Then
Do
i = i + 1
path = Filename & i & extension
Loop While File.Exists(path)
End If
cap.Filename = path
cap.Cue()
cap.Start()
ButtonVIDEO.BackColor = Color.Red
ButtonVIDEO.Text = "PLAYING"
ButtonPHOTO.Hide()
End If
End Sub
The path should have only one backslash in c:\folder. In VB strings are concatenated with &, not +.
See answer to The difference between + and & for joining strings in VB.NET

Related

Making a program that zip files but having error The process cannot access the file because it is being used by another process

I am trying to make a program that will zip all the files in the same folder.
But I'm having issues with it. It's giving me an error saying the file is being used by another process.
Private Sub btnZip_Click(sender As Object, e As EventArgs) Handles btnZip.Click
Dim extension As String = txtExtension.Text
Dim paths As String = Application.StartupPath
Dim files As String() = Directory.GetFiles(paths, "*.*")
For Each file As String In files
Dim fileName As String = path.GetFileNameWithoutExtension(file)
Dim index As Integer = fileName.IndexOf("_")
If index >= 0 Then
fileName = fileName.Substring(0, index)
End If
ZipFile.CreateFromDirectory(Path.GetDirectoryName(file), paths & "\" & fileName & ".zip", CompressionLevel.Optimal, False)
Next
MessageBox.Show("Files zipped successfully!")
End Sub
I just couldn't figure out what's causing the issue.
as seen in comment, you must exclude your running application from the file list :
add
If Path.GetFileName(file) = Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) Then Continue For
in for loop
Private Sub btnZip_Click(sender As Object, e As EventArgs) Handles btnZip.Click
Dim extension As String = txtExtension.Text
Dim paths As String = Application.StartupPath
Dim files As String() = Directory.GetFiles(paths, "*.*")
For Each file As String In files
If Path.GetFileName(file) = Path.GetFileName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) Then Continue For
Dim fileName As String = Path.GetFileNameWithoutExtension(file)
Dim index As Integer = fileName.IndexOf("_")
If index >= 0 Then
fileName = fileName.Substring(0, index)
End If
ZipFile.CreateFromDirectory(Path.GetDirectoryName(file), paths & "\" & fileName & ".zip", CompressionLevel.Optimal, False)
Next
MessageBox.Show("Files zipped successfully!")
End Sub

Search For ID number In TextFile vb.net

This is what i need to do, I click on the openfile button and brings up the openfile dialog box. I open a textfile and it gets displayed in the informationbox.text field, at the same time i would like to search that file for an ID number and display it in the IDbox.text field.
i have searched other forums, but they just use the Replace method or other methods that i don't know about. It becomes too confusing.
This is what i have so far -
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
Dim oReader As StreamReader
OpenFileDialog1.CheckFileExists = True
OpenFileDialog1.CheckPathExists = True
OpenFileDialog1.DefaultExt = "txt"
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
OpenFileDialog1.Multiselect = False
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
oReader = New StreamReader(OpenFileDialog1.FileName, True)
InformationBox.Text = oReader.ReadToEnd
My.Forms.Home.TextBox5.AppendText(Environment.NewLine & "Opened Customer : " & OpenFileDialog1.FileName & " File")
oReader.Close()
End If
IDBox.Text = ""
Label11.Text = OpenFileDialog1.FileName
End Sub
example of textfile :
Name of customer : Name
Surname of customer :Surname
ID number : 12345678910
Record number : 001
Address of Customer : Address
Can anyone help me please?
In your example code you use StreamReader to read the text file.
The "drawback" of Streams is that you have to manage their disposing manually.
In your example, if an error occurs in oReader.ReadToEnd the line oReader.Close will not be hit and the Stream might remain undisposed thus causing trouble.
So you´d better enclosure your Stream in a Using scope (another option would be to use static System.IO.File.ReadAllLines|ReadAllText methods).
Private Sub OpenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles OpenToolStripMenuItem.Click
'Dim oReader As StreamReader <-- DELETE THIS
OpenFileDialog1.CheckFileExists = True
OpenFileDialog1.CheckPathExists = True
OpenFileDialog1.DefaultExt = "txt"
OpenFileDialog1.FileName = ""
OpenFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*"
OpenFileDialog1.Multiselect = False
If OpenFileDialog1.ShowDialog = Windows.Forms.DialogResult.OK Then
'MY CODE STARTS HERE:
Dim customerInfo As String
Using sr = New StreamReader(OpenFileDialog1.FileName, True)
customerInfo = sr.ReadToEnd()
End Using 'Close the stream early since we have all data needed
'Write all lines into a string array
Dim lines As String() = customerInfo.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
'Get the line where the ID Number is in
Dim idLine As String = lines.Where(Function(l) l.StartsWith("ID number")).FirstOrDefault()
Dim id As String = String.Empty
If Not String.IsNullOrEmpty(idLine) Then
Dim aIdLine() = idLine.Split(":"c) 'Split the ID line by :
If aIdLine.Length >= 1 Then
id = aIdLine(1) 'This should be the actual ID
End If
End If
'Set UI
My.Forms.Home.TextBox5.AppendText(Environment.NewLine & "Opened Customer : " & OpenFileDialog1.FileName & " File")
InformationBox.Text = customerInfo
IDBox.Text = id
Label11.Text = OpenFileDialog1.FileName
End If

VB2010 reading a text file into a datagridview but only certain fields/lines

I am trying to read through a text file but then displaying ONLY certain fields back to my DataGridView, not the whole file. I set the delimiter as " + " and then want to show the file where the field starts with for example EQD.
My file looks something like this where each line is sepearted by a " ' ":
UNB+UNOA:1+++160804:0850+1+++++1'
UNH+402+BAPLIE:1:911:UN:SMDG15'
BGM++580691+9'
DTM+137:2016080408 50:301'
TDT+20+6217++++MACS:172:166'
LOC+5+NAWVB:139:6'
LOC+61+ZACPT:139:6'
DTM+178:1608020718:201'
DTM+133:1607030700:201'
DTM+132:160702:101'
LOC+147+0121282::5'
MEA+WT++KGM:4200'
LOC+6+PTLEI'
LOC+12+ZADUR'
RFF+BM:1'
****EQD+CN+CXRU1123659+45R1+++4'****
NAD+CA+MACS:172:20'
UNT+2339+402'
UNZ+1+1'
The code I currently have is:
Imports System.IO
Imports System.Text.RegularExpressions
Imports System
Imports System.Collections
Public Class Form1
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim sourceFilename1 As String
'Dim finalFile As List(Of String) = New List(Of String)
'Dim origFileData() As String = File.ReadAllText(sourceFilename1).Replace(vbCr, "").Replace(vbLf, "").Split({"'"}, StringSplitOptions.RemoveEmptyEntries)
OpenFileDialog1.Filter = "BAPLIE Files (*.*;*.*)|*.*;*.*"
If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then
sourceFilename1 = OpenFileDialog1.FileName
End If
Dim TextFieldParser1 As New Microsoft.VisualBasic.FileIO.TextFieldParser(sourceFilename1)
TextFieldParser1.Delimiters = New String() {"'"}
TextFieldParser1.ReadLine.StartsWith("EQD+CN+")
'If sourceFilename1.StartsWith("EQD+CN+") Then
' numberString = sourceFilename1.Substring(sourceFilename1.IndexOf("CN+"), 14)
' txtLastName.Text = numberString.Substring(3)
'End If
While Not TextFieldParser1.EndOfData
Dim Row1 As String() = TextFieldParser1.ReadFields()
If DataGridView1.Columns.Count = 0 AndAlso Row1.Count > 0 Then
Dim i As Integer
For i = 0 To Row1.Count - 1
DataGridView1.Columns.Add("Column" & i + 1, "Column" & i + 1)
Next
End If
DataGridView1.Rows.Add(Row1)
End While
End Sub
End Class
I am not experienced at programming and doing this as a pet project.
I have re-written my code. I get my file to display the correct info on one line only, BUT now it only show ONE line in my datagrid if I run my program?
here is my new code:
Imports System.IO
Imports System.Text.RegularExpressions
Imports System
Imports System.Collections
Public Class Form1
'------THIS IS GOOD
Private Sub btnRun_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRun.Click
Dim sourceFilename2 As String = "*.edi | *.txt"
If OpenFileDialog1.ShowDialog(Me) = DialogResult.OK Then
sourceFilename2 = OpenFileDialog1.FileName
End If
Dim strm As IO.Stream = IO.File.OpenRead(sourceFilename2)
Dim sr As New IO.StreamReader(strm)
Dim sw = System.Diagnostics.Stopwatch.StartNew()
Dim line1 As String = ""
Dim trimchars() As Char = {"+", "'"}
grdMydata.Columns.Add("Column1", "POD") ' ------------------------- INDEX 0
grdMydata.Columns.Add("Column2", "BAY") ' ------------------------- INDEX 1
grdMydata.Columns.Add("Column3", "SLOT") ' ------------------------ INDEX 2
grdMydata.Columns.Add("Column4", "VGM WEIGHT") ' ------------------ INDEX 3
grdMydata.Columns.Add("Column5", "WT WEIGHT") ' ------------------- INDEX 4
grdMydata.Columns.Add("Column6", "CONTAINER ID") ' ---------------- INDEX 5
grdMydata.Columns.Add("Column7", "ISO CODE") ' -------------------- INDEX 6
grdMydata.Columns.Add("Column8", "FULL/EMPTY") ' ------------------ INDEX 7
grdMydata.Columns.Add("Column9", "CARRIER") ' --------------------- INDEX 8
Do While sr.Peek() <> -1
Dim Newline As String
Newline = System.Environment.NewLine
line1 = sr.ReadLine()
'-----------------The file info in the text box
'txtTopRows.Text = UNH+402+ & BAPLIE:1:911:UN:SMDG15' BAPLIE VERSION
If line1.Contains("SMDG15") Then
txtTopRows.Text = "BAPLIE ver 1.5 "
End If
If line1.Contains("SMDG20") Then
txtTopRows.Text = "BAPLIE ver 2.0 "
End If
If line1.Contains("SMDG22") Then
txtTopRows.Text = "BAPLIE ver 2.0 "
End If
'DTM+137:2016080408 50:301'
If line1.Contains("DTM+137") Then
txtTopRows.Text = txtTopRows.Text & Newline & "File Date : " & (line1.Substring(8, 10))
End If
'Port of load here
If line1.Contains("LOC+5") Then
txtTopRows.Text = txtTopRows.Text & Newline & "Port of Load : " & (line1.Substring(6, 5))
End If
'Port of Discharge here
If line1.Contains("LOC+61") Then
txtTopRows.Text = txtTopRows.Text & Newline & "Port of Disharge : " & (line1.Substring(7, 5))
End If
'-----------------------------------------------------------------------------------------
Dim row1 As Integer = Me.grdMydata.Rows.Add()
'grdMydata.Rows.Clear()
'''''Code to get all data on ONE row
row1 = grdMydata.CurrentCell.RowIndex
If line1.TrimStart(trimchars).StartsWith("LOC+147") Then
grdMydata.Rows(row1).Cells(1).Value = (line1.Substring(8, 3))
grdMydata.Rows(row1).Cells(2).Value = (line1.Substring(8, 7))
End If
If line1.TrimStart(trimchars).StartsWith("MEA+VGM") Then
grdMydata.Rows(row1).Cells(3).Value = (line1.Substring(13, 5))
End If
If line1.TrimStart(trimchars).StartsWith("MEA+WT") Then
grdMydata.Rows(row1).Cells(4).Value = (line1.Substring(12, 5))
End If
If line1.TrimStart(trimchars).StartsWith("EQD") Then
grdMydata.Rows(row1).Cells(5).Value = (line1.Substring(7, 11))
grdMydata.Rows(row1).Cells(6).Value = (line1.Substring(19, 4))
End If
If line1.TrimStart(trimchars).StartsWith("NAD+CA") Then
grdMydata.Rows.Item(row1).Cells(8).Value = (line1.Substring(7, 3))
End If
Dim blank As Boolean = True
For Each _row As DataGridViewRow In grdMydata.Rows
blank = True
For i As Integer = 0 To _row.Cells.Count - 1
If _row.Cells(i).Value IsNot Nothing AndAlso _row.Cells(i).Value <> "" Then
blank = False
Exit For
End If
Next
If blank Then
If Not _row.IsNewRow Then
grdMydata.Rows.Remove(_row)
End If
End If
Next
Loop
sr.Close()
sourceFilename2 = Nothing
sw.Stop()
txtDisplay1.Text = String.Format("File loaded in: {0} miliseconds" _
& vbCrLf & "Number of Containers: {1}", sw.ElapsedMilliseconds, grdMydata.Rows.Count)
'MsgBox ("Hai" & vbCrLf & "Welcome")
End Sub
Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
Dim sourceFilename1 As String
Dim sw = System.Diagnostics.Stopwatch.StartNew()
sourceFilename1 = Nothing
sw.Stop()
Me.Close()
End Sub
End Class
If none of the values in the file contain + or ', then you can use the Split function:
Dim text = File.ReadAllText(sourceFilename1)
Dim lines = Split(text, "'")
For Each line in lines
Dim values = Split(line, "+")
DataGridView1.Rows.Add(values)
Next

creating more than one image file when button clicked

Private Sub btnPrint_Click(sender As Object, e As EventArgs) Handles btnPrint.Click
CaptureScreen()
'used to created file path
Dim orderNum As String = Val(txtNum.Text) 'gets value of Invoice/PO number
Dim orderType As String = GroupBox3.Text 'gets value of either its a Invoice or PO`
'saves printscreen to PictureBox
PictureBox1.Image = bmpBackground
'saves printscreen to file path
PictureBox1.Image.Save("\\PCLIQFS\Shared_Data\PCLiq Scale-Shots\" + orderType + " " + orderNum + ".jpg", Imaging.ImageFormat.Jpeg)
'creates variable of filePath
Dim filePath As String = "\\PCLIQFS\Shared_Data\PCLiq Scale-Shots\" + orderType + " " + orderNum + ".jpg"
'checks to see if file is already in filePath
If File.Exists(filePath) Then
Dim folderPath = Path.GetDirectoryName(filePath)
Dim fileName = Path.GetFileNameWithoutExtension(filePath)
Dim extension = Path.GetExtension(filePath)
Dim fileNumber = 0
Do
'increments file name
fileNumber += 1
filePath = Path.Combine(folderPath,
String.Format("{0} ({1}){2}",
fileName,
fileNumber,
extension))
Loop While File.Exists(filePath)
End If
'saves new image
PictureBox1.Image.Save(filePath)
End Sub
I want to save an image when the user clicks the print button, but it creates two images at once since the images is already there. I only want to create another image if the print button is clicked again. How to I make it so that the code the increments the file name only runs if the print button is clicked again?
Comment the following line;
PictureBox1.Image.Save("\\PCLIQFS\Shared_Data\PCLiq Scale-Shots\" + orderType + " " + orderNum + ".jpg", Imaging.ImageFormat.Jpeg)
because you are saving the image at the end of the code.

Crystal report export in excel

Having problem in my crystal report, exporting to excel. Can somebody help me how to code or any suggestion code that will catch if the file you exported is already exist?
For example, you exported lotinfo the next will be lotinfo2 then lotinfo3 etc, my code is always exporting single file and single name.
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Try
Dim CrExportOptions As ExportOptions
Dim CrDiskFileDestinationOptions As New _
DiskFileDestinationOptions()
Dim CrFormatTypeOptions As New ExcelFormatOptions
CrDiskFileDestinationOptions.DiskFileName = _
"c:\Lot Enterprise Information.xls"
CrExportOptions = crypt.ExportOptions
With CrExportOptions
.ExportDestinationType = ExportDestinationType.DiskFile
.ExportFormatType = ExportFormatType.Excel
.DestinationOptions = CrDiskFileDestinationOptions
.FormatOptions = CrFormatTypeOptions
End With
crypt.Export()
MessageBox.Show("LOT ENTERPRISE INFORMATION IS SUCCESSFULLY EXPORTED!, LOCATED AT DRIVE C:", "PLEASE CHECK AT DRIVE C:", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
MsgBox("Please Select Specific date to convert!")
'MsgBox(ex.ToString)
End Try
End Sub
I've been using this function for quite some time now. Just fix it up depending on your use.
Private Function fileExists(ByVal path As String, ByVal filename As String) As String
' This function basically adds a counter when the file already exists
' eg filename
' filename(1)
' filename(2)
Dim counter As Integer = 0
Dim orginialFileName As String = System.IO.Path.Combine(path, filename)
Dim newFileName = orginialFileName
Dim extension As String = ""
Dim testIndex As Integer = 0
While File.Exists(newFileName)
counter = counter + 1
extension = newFileName.Substring(newFileName.LastIndexOf("."))
filename = filename.Substring(0, filename.LastIndexOf("."))
testIndex = filename.LastIndexOf("(")
If testIndex <> -1 Then
filename = filename.Substring(0, testIndex)
End If
newFileName = String.Format("{0}({1})", System.IO.Path.Combine(path, filename), counter.ToString())
filename = String.Format("{0}({1})", filename, counter.ToString())
newFileName += extension
filename += extension
End While
Return filename
End Function
example usage
Dim output as string
output = fileExists("C:\test", "file.xls")
MsgBox(output)
This link might also be useful for you.
EDIT:
You can use it before your Try-Catch block
Dim fullPath As String = "C:\fileinfo.xls"
Dim directory, output, filename As String
If File.Exists(fullPath) Then
directory = fullPath.Substring(0, fullPath.LastIndexOf("\"))
filename = fullPath.Substring(fullPath.LastIndexOf("\") + 1)
output = fileExists(directory, filename)
fullPath = path.combine(directory,output)
End If
Then change this part
CrDiskFileDestinationOptions.DiskFileName = _
"c:\Lot Enterprise Information.xls"
To
CrDiskFileDestinationOptions.DiskFileName = _
fullPath