How To Create Automated Backup Files In Vb.Net Application? - vb.net

How to create automated backup files and backup type compress.
But I want to backup the folder containing Data Files (.doc,.xls,.tiff,.pdf...) but not sql database.
I Want file Backup SHARE-AC.zip. But now have get folder SHARE-AC don't zip.
Imports System.IO
Imports System.IO.Compression
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim dstr As String
Dim mstr As String
Dim ystr As String
Dim folstr As String
Dim dsumstr As String
dstr = DateTime.Today.ToString("dd")
mstr = DateTime.Today.ToString("MM")
ystr = DateTime.Today.ToString("yyyy")
dsumstr = ystr & "-" & mstr & "-" & dstr
folstr = "Y:\server1\Fileserver-" & dsumstr
Try
My.Computer.FileSystem.CreateDirectory(folstr)
My.Computer.FileSystem.CreateDirectory(folstr & "\SHARE-AC")
My.Computer.FileSystem.CopyDirectory("D:\SHARE-AC", folstr & "\SHARE-AC")
Label1.Text = "Back up DATE " & dsumstr & " Complete"
Catch ex As Exception
Label1.Text = (ex.Message)
End Try
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Close()
End Sub
End Class

i dont get your question but If you just wanna zip your file you can use this
Update : You could use GZipStream in the System.IO.Compression namespace
.NET 2.0.
Public Shared Sub CompressFile(path As String)
Dim sourceFile As FileStream = File.OpenRead(path)
Dim destinationFile As FileStream = File.Create(path & ".gz")
Dim buffer As Byte() = New Byte(sourceFile.Length - 1) {}
sourceFile.Read(buffer, 0, buffer.Length)
Using output As New GZipStream(destinationFile, CompressionMode.Compress)
Console.WriteLine("Compressing {0} to {1}.",sourceFile.Name,destinationFile.Name, False)
output.Write(buffer, 0, buffer.Length)
End Using
' Close the files.
sourceFile.Close()
destinationFile.Close()
End Sub
.NET 4
Public Shared Sub Compress(fi As FileInfo)
' Get the stream of the source file.
Using inFile As FileStream = fi.OpenRead()
' Prevent compressing hidden and
' already compressed files.
If (File.GetAttributes(fi.FullName) And FileAttributes.Hidden) <> FileAttributes.Hidden And fi.Extension <> ".gz" Then
' Create the compressed file.
Using outFile As FileStream = File.Create(Convert.ToString(fi.FullName) & ".gz")
Using Compress As New GZipStream(outFile, CompressionMode.Compress)
' Copy the source file into
' the compression stream.
inFile.CopyTo(Compress)
Console.WriteLine("Compressed {0} from {1} to {2} bytes.", fi.Name, fi.Length.ToString(), outFile.Length.ToString())
End Using
End Using
End If
End Using
End Sub

if you want to zip the file on the directory you set use this code :
Dim dstr As String
Dim mstr As String
Dim ystr As String
Dim folstr As String
Dim dsumstr As String
dstr = DateTime.Today.ToString("dd")
mstr = DateTime.Today.ToString("MM")
ystr = DateTime.Today.ToString("yyyy")
dsumstr = ystr & "-" & mstr & "-" & dstr
folstr = "Y:\server1\Fileserver-" & dsumstr
Try
My.Computer.FileSystem.CreateDirectory(folstr)
My.Computer.FileSystem.CreateDirectory(folstr & "\SHARE-AC")
ZipFile.CreateFromDirectory("D:\SHARE-AC", folstr & "\SHARE-AC\myfile.zip") ' Zip all file in your directory
'My.Computer.FileSystem.CopyDirectory("D:\SHARE-AC", folstr & "\SHARE-AC")
Label1.Text = "Back up DATE " & dsumstr & " Complete"
Catch ex As Exception
Label1.Text = (ex.Message)
End Try
End Sub
YOU NEED TO IMPORT:
Imports System.IO
Imports System.IO.Compression
UPDATE
You can use SharpZipLip
And here some Examples.

Related

How to create a progress bar that updates simultaneously with a file transfer

As the title implies, I am trying to create a progress bar that updates with a file transfer. I am currently using Visual Studio 2019. I have been through dozens of articles and videos all claiming to do just this. After many days of testing, I have gotten close, but the progress bar will still only update after the file transfer is complete. I am using multi threading techniques to accomplish just this much. I would very much appreciate if someone could just lay it down for me on how to do this. Here is my code so far. It doesn't really help for making it but you can at least see what I am trying to achieve. I also left out some large chunks of commented out test script.
Summary of what I need to is: Create a script that will copy the specified directory and all sub directories. While doing this I would like the progress bar to move with the file transfer.
Imports System.ComponentModel
Imports System.Threading
Imports System
Imports System.IO
Public Class Form1
Private Sub BtnStartTransfer_Click(sender As Object, e As EventArgs) Handles btnStartTransfer.Click
BackgroundWorker1.RunWorkerAsync()
End Sub
Private Delegate Sub DelegateProgressBarMax(ByVal check As Integer)
Private Sub ProgressBarUpdate(ByVal check As Integer)
If pBar1.InvokeRequired = True Then
Invoke(Sub() pBar1.Value = check)
Else
pBar1.Value = check
End If
End Sub
Private Delegate Sub DelegateUpdateOutput(ByVal check2 As String)
Private Sub OutputUpdate(ByVal check2 As String)
If txtOutput.InvokeRequired = True Then
Invoke(Sub() txtOutput.Text = txtOutput.Text & check2 & Environment.NewLine)
Else
txtOutput.Text = txtOutput.Text & check2
End If
End Sub
Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
Dim getCopyFrom As String = txtCopyFrom.Text
Dim getCopyTo As String = txtCopyTo.Text
Dim splitUser() As String = getCopyFrom.Split("\")
Dim finalValue As String = splitUser.Length - 1
Dim stringValue As String = CStr(splitUser(finalValue))
Dim getUser As String
'If MsgBox("Is this the correct user?: " & stringValue, vbYesNo + vbQuestion) = vbYes Then
' getUser = stringValue
'Else
' getUser = InputBox("Enter in the correct Username")
'End If
Dim checkCopyFrom As New IO.DirectoryInfo(getCopyFrom)
Dim checkCopyTo As New IO.DirectoryInfo(getCopyTo)
If checkCopyFrom.Exists Then
Else
MsgBox("The location you are trying to copy from does not exist.")
Exit Sub
End If
If checkCopyTo.Exists Then
Else
MsgBox("The location you are trying to copy to does not exist.")
Exit Sub
End If
'Copying the Desktop folder
Dim dirDesktop = getCopyFrom & "\Desktop"
Dim getDir = IO.Directory.GetFiles(dirDesktop, "*", IO.SearchOption.AllDirectories)
Dim fileTotal As Integer = getDir.Length
Dim filesTransferred As Integer = 0
Dim di As New DirectoryInfo(dirDesktop)
Dim fiArr As FileInfo() = di.GetFiles("*", SearchOption.AllDirectories)
Dim diArr As DirectoryInfo() = di.GetDirectories("*", IO.SearchOption.AllDirectories)
Dim fri As FileInfo
Dim fol As DirectoryInfo
For Each fri In fiArr
filesTransferred += 1
BackgroundWorker1.ReportProgress(CInt(filesTransferred * 100 \ fiArr.Length), True)
OutputUpdate(fri.Name)
'File.Copy(dirDesktop & "\" & fri.Name, getCopyTo & "\" & fri.Name, True)
'My.Computer.FileSystem.CopyDirectory(getCopyFrom & "\Desktop", getCopyTo & "\Users\" & getUser & "\Desktop", False)
Next fri
End Sub
Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
pBar1.Value = e.ProgressPercentage
End Sub

Type expected error VB.Net

Error ImagePlease assist, I get a "Type expected" error on my code for a windows based application. I get the error on this line "Dim objSW As New StreamWriter(objFS)"
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim strFileName As String = My.Application.Info.DirectoryPath & "\empout_fixed.txt"
Dim objFS As New FileStream(strFileName, FileMode.Create, FileAccess.Write)
Dim objSW As New StreamWriter(objFS)
Dim strEmpName As String
Dim intDeptNbr As Integer
Dim strJobTitle As String
Dim dtmHireDate As Date
Dim sngHrlyRate As Single
strEmpName = “Thabo Lereko”
intDeptNbr = 1001
strJobTitle = “Junior Programmer”
dtmHireDate = #10/05/2014#
sngHrlyRate = 99.99
' Write out the record to the file ...
objSW.WriteLine(strEmpName.PadRight(20) &
intDeptNbr.ToString.PadLeft(4) &
Space(5) &
strJobTitle.PadRight(21) &
Format(dtmHireDate, "M/d/yyyy").PadRight(10) &
Format(sngHrlyRate, "Standard").PadLeft(5))
MsgBox("Record was written to the output file.")
objSW.Close()
End Sub
End Class
The problem is that you have named your project "StreamWriter", which causes "StreamWriter" to refer to the namespace of the project. Maybe you should use more a bit more descriptive project names in the future just for clarity?
You can fix this by referring to the real StreamWriter with namespace:
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim strFileName As String = My.Application.Info.DirectoryPath & "\empout_fixed.txt"
Using objFS As New FileStream(strFileName, FileMode.Create, FileAccess.Write)
Using objSW As New System.IO.StreamWriter(objFS)
Dim strEmpName As String
Dim intDeptNbr As Integer
Dim strJobTitle As String
Dim dtmHireDate As Date
Dim sngHrlyRate As Single
strEmpName = “Thabo Lereko”
intDeptNbr = 1001
strJobTitle = “Junior Programmer”
dtmHireDate = #10/05/2014#
sngHrlyRate = 99.99
' Write out the record to the file ...
objSW.WriteLine(strEmpName.PadRight(20) &
intDeptNbr.ToString.PadLeft(4) &
Space(5) &
strJobTitle.PadRight(21) &
Format(dtmHireDate, "M/d/yyyy").PadRight(10) &
Format(sngHrlyRate, "Standard").PadLeft(5))
MsgBox("Record was written to the output file.")
End Using
End Using
End Sub
End Class
Ps. Added the using-statements that should always be used with iDisposable-objects. Removed the unnecessary close-call also.

Save pictures while I scrape them from website using VB.NET

I find a code on YouTube when I use it on my visual basic and debug it and find pictures but when i want to save them software gives me this message here.
Private Sub btnSaveImages_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
btnSaveImages.Click
Dim dir_name As String = txtDirectory.Text
If Not dir_name.EndsWith("\") Then dir_name &= "\"
For Each pic As PictureBox In flpPictures.Controls
Dim bm As Bitmap = pic.Image
Dim filename As String = pic.Tag
filename = _
filename.Substring(filename.LastIndexOf("/") + _
1)
Dim ext As String = _
filename.Substring(filename.LastIndexOf("."))
Dim full_name As String = dir_name & filename
Select Case ext
Case ".bmp"
bm.Save(full_name, Imaging.ImageFormat.Bmp)
Case ".gif"
bm.Save(full_name, Imaging.ImageFormat.Gif)
Case ".jpg", "jpeg"
bm.Save(full_name, Imaging.ImageFormat.Jpeg)
Case ".png"
bm.Save(full_name, Imaging.ImageFormat.Png)
Case ".tiff"
bm.Save(full_name, Imaging.ImageFormat.Tiff)
Case Else
MessageBox.Show( _
"Unknown file type " & ext & _
" in file " & filename, _
"Unknown File Type", _
MessageBoxButtons.OK, _
MessageBoxIcon.Error)
End Select
Next pic
Beep()
End Sub
The issue is that LastIndexOf isn't finding . in your filename. This then passes -1 to to SubString which throws the error you're seeing.
Instead of writing the file parsing yourself use the methods of System.Io.Path such as
System.IO.Path.GetDirectoryName(filename)
System.IO.Path.GetFileName(filename)
System.IO.Path.GetFileNameWithoutExtension(filename)
Private Sub btnSaveImages_Click(ByVal sender As _
System.Object, ByVal e As System.EventArgs) Handles _
btnSaveImages.Click
For Each pic As PictureBox In flpPictures.Controls
Dim bm As Bitmap = pic.Image
Dim path As String = pic.Tag
Dim filename = IO.Path.GetFileName(path)
Dim ext = IO.Path.GetExtension(path)
Dim full_name = IO.Path.Combine(txtDirectory.txt, filename)
....

Read String From Serial port Visual Basic

Imports System.IO.Ports
Imports System.Text
Public Class Form4
Dim myStringBuilder As String
Dim insert As New OleDb.OleDbCommand
Dim cnn As New OleDb.OleDbConnection
Public user As String
Private Sub Serialport2_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort2.DataReceived
myStringBuilder = SerialPort2.ReadExisting()
Me.Invoke(New EventHandler(AddressOf UpdateControls))
End Sub
Private Sub UpdateControls(ByVal sender As Object, ByVal e As EventArgs)
Dim A As String = myStringBuilder
Dim Sqql As String
If Not cnn.State = ConnectionState.Open Then
cnn.Open()
End If
insert.Connection = cnn
Dim dt As New DataTable
Sqql = "SELECT * FROM `FileInfo` WHERE `File ID`='" & A & "'"
Dim cmd As New OleDb.OleDbDataAdapter(Sqql, cnn)
cmd.Fill(dt)
Dim i As Integer = dt.Rows.Count
Dim todaysdate As String = String.Format("{0:dd/MM/yyyy}", DateTime.Now)
If i = 1 Then
insert.CommandText = "INSERT INTO `File Log`(File ID,Name,Information,Time,Date) " & _
" VALUES('" & A & "','" & dt.Rows(0).Item("Name") & "','" & user & " telah" & dt.Rows(0).Item("Status") & "File" & "','" &
_
TimeOfDay & "','" & todaysdate & "')"
textBox1.Text += dt.Rows(0).Item("Name") & " " & TimeOfDay & " " & todaysdate &
Environment.NewLine
textBox1.Select(textBox1.TextLength, 0)
textBox1.ScrollToCaret()
insert.ExecuteNonQuery()
myStringBuilder = ""
Else
myStringBuilder = ""
textBox1.Text += A & Environment.NewLine
End If
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
cnn = New OleDb.OleDbConnection
cnn.ConnectionString = "Provider=Microsoft.Jet.Oledb.4.0; Data Source=" & Application.StartupPath & "\data.mdb"
If SerialPort2 IsNot Nothing Then
SerialPort2.Close()
End If
SerialPort2 = My.Computer.Ports.OpenSerialPort("COM27", 9600, Parity.None, 8, StopBits.One)
textBox1.Text = "-- Door Have Open -- " & Environment.NewLine & Environment.NewLine
End Sub
Private Sub textBox1_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles textBox1.TextChanged
End Sub End Class
in my serial monitor view it will appear correctly but in visual basic it will auto break line and not display the string in one line.
I Tried other method like serialport.readline() but nothing happen.
If you are having issues with extracting data from your serial port you could try this:
Sub SerialPort_DataReceived(sender As Object, e As SerialDataReceivedEventArgs)
Dim currentSP As SerialPort = Convert.ChangeType(sender, GetType(SerialPort))
Dim strBuilder As System.Text.StringBuilder = New System.Text.StringBuilder()
For index = 1 To currentSP.BytesToRead
strBuilder.Append(Convert.ChangeType(currentSP.ReadByte(), GetType(Char)))
Next
' Have a global string to allow the threads to have a shared resource
myString = strBuilder.ToString()
Me.Invoke(New EventHandler(AddressOf UpdateControls))
End Sub
It should work the same way as the SerialPort.ReadLine(), this approach also lets you manipulate the data however you want. Instead of working with a string you could always work the data like this:
Dim buffer As Byte() = New Byte(currentSP.BytesToRead) {}
buffer(index) = Convert.ChangeType(currentSP.ReadByte(), GetType(Byte))
So instead of appending the Char to the String you can add the Byte to the buffer
Dim str As String = MyCOMPort.ReadExisting()
If Me.InvokeRequired Then
Me.Invoke(New dlUpdateText(AddressOf updatetext), str)
Else
updatetext(str)
End If

vb.net Searching for specific lines within large .log files

I'm reading from 1-5mb log files outputting to a textview and also searching for specific lines outputting to another textview. Currently it takes about a minute for just a 1mb file. Does anyone know any faster methods of searching through lines or strings other than the method I'm using?
Imports EnterpriseDT.Net.Ftp
Public Class Form1
Private Sub SettingsToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles SettingsToolStripMenuItem.Click
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
Dim sw As New Stopwatch
Dim FullLine As String = ""
Dim ScriptLine As String = ""
sw.Start()
Dim ll As New Queue(Of String)
Dim i As String = ""
Using TestFile As New IO.StreamReader("c:\test.txt", System.Text.Encoding.Default, False, 4096)
Using OutFile As New IO.StreamWriter("c:\SBOutFile.txt", False, System.Text.Encoding.Default, 4096)
While TestFile.EndOfStream = False
i = TestFile.ReadLine
If i.Contains(".sqf") And i.Contains("handleGear.sqf") = False Then
ScriptLine = ScriptLine & i & vbNewLine & vbNewLine
FullLine = FullLine & i & vbNewLine & vbNewLine
Else
FullLine = FullLine & i & vbNewLine & vbNewLine
End If
End While
End Using
End Using
sw.Stop()
TextBox1.Text = FullLine
TextBox2.Text = ScriptLine
RichTextBox1.AppendText(String.Format("Run_Queue took {0} Milliseconds." & Environment.NewLine, sw.ElapsedMilliseconds))
End Sub
Private Sub Button1_Click_1(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Try
'connect to ftp server
Dim ftp As New FTPConnection
ftp.ServerAddress = "-"
ftp.ServerPort = "-"
ftp.UserName = "-"
ftp.Password = "-"
ftp.Connect()
ftp.ChangeWorkingDirectory("-")
ftp.TransferType = FTPTransferType.BINARY
'download a file
ftp.DownloadFile("c:\test.txt", "scripts.log")
'ftp.RenameFile("scripts.log", "scripts_test.log")
'close the connection
ftp.Close()
Catch ex As Exception
MessageBox.Show(ex.Message.ToString())
End Try
End Sub
Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) Handles Button3.Click
End Sub
End Class
Given the heavy reading and concatenating you are doing as you're reading, I suspect its part of your time/performance issue. I would probably consider changing the declarations for ScriptLine and FullLine from String type to a StringBuilder, because Strings are technically immutable. That means each concatenation really turns out to be teardown of the previous object, and the creation of a new one in its place. StringBuilders are designed specifically for heavy concatenation scenarios. When the looping is finished, you can convert it back to a String.
Also, a compiled Regular Expression might search faster than String.Contains. Your regular expression string would be something like "(?!handleGear).sqf", meaning "find any sequence of zero or more characters other than "handleGear" in front of the string ".sqf".
I haven't had a chance to test that expression, so it is offered with that caveat. If I get a chance to throw together a test, I'll be glad to amend and let you know.
Good luck!
I just wanted to post what I came up with in the end. It was a very large improvement to what I had.
'Read file
Dim sw As New Stopwatch
Dim FullLine As String = ""
Dim ScriptLine As String = ""
sw.Start()
Dim ll As New Queue(Of String)
Dim i As String = ""
Dim builder As New StringBuilder
Using TestFile As New IO.StreamReader("c:\test.txt", System.Text.Encoding.Default, False, 4096)
builder.AppendLine("Started at: " & DateTime.Now.ToLongTimeString().ToString)
RichTextBox1.AppendText(Now.ToShortTimeString & " Reading Log File Started" & vbNewLine)
RichTextBox1.SelectionStart = RichTextBox1.TextLength
Dim rowCount As Integer = 0
Do Until TestFile.EndOfStream
ScriptLine = TestFile.ReadLine
ScriptLine = LCase(ScriptLine)
If InStr(ScriptLine, ".sqf") > 0 And InStr(ScriptLine, "handlegear.sqf") < 1 Then 'And InStr(ScriptLine, "createmarkerlocal.sqf") < 1 And InStr(ScriptLine, "setmarkerposlocal.sqf") < 1
builder.AppendLine(ScriptLine)
builder.AppendLine()
End If
rowCount = rowCount + 1
Loop
builder.AppendLine(Now.ToShortTimeString & "==== Searched " & rowCount & " rows" & vbNewLine)
builder.AppendLine(Now.ToShortTimeString & " Finished" & vbNewLine)
End Using
sw.Stop()
RichTextBox2.AppendText(builder.ToString & vbNewLine)
RichTextBox1.AppendText(Now.ToShortTimeString & String.Format(" Run_Queue took {0} Milliseconds." & Environment.NewLine, sw.ElapsedMilliseconds))