VB2008 Changing string in a file - vb.net

I want to change something on a compiled game file, so I used this code:
Private Sub Next2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Next2.Click
Dim reader As New System.IO.StreamReader("Languages/" & Language & ".Devil")
Dim allLines As List(Of String) = New List(Of String)
Do While Not reader.EndOfStream
allLines.Add(reader.ReadLine())
Loop
reader.Close()
Tips.Text = ReadLine(6, allLines)
WeaponsListBox.Hide()
NewWeaponsList.Hide()
Next2.Hide()
Dim curItem As String = WeaponsListBox.SelectedItem.ToString()
Dim curItem2 As String = NewWeaponsList.SelectedItem.ToString()
Try
If MainWeapon = "Cheytac" Then
Dim supahotfire As String = curItem.Substring(0, 12)
Dim hotdestroyer As String = curItem.Replace(supahotfire, "")
Dim supa2 As String = curItem2.Substring(0, 12)
Dim hot2 As String = curItem2.Replace(supa2, "")
Dim oldfile As String = "pack/Weapon_" & curItem & ".i3pack"
Dim FileName As String = "pack/pack_" & MainWeapon & hot2 & "_" & hotdestroyer & ".i3pack"
Dim be = My.Computer.FileSystem.ReadAllBytes(oldfile)
Dim be2 As String = UnicodeBytesToString(be)
be2.Replace("Weapon\" & curItem & "/" & curItem & "_diff", "Weapon\" & curItem2 & "/" & curItem2 & "_diff")
Dim be3 As String = be2.Replace("Weapon\" & curItem & "/Cheytac_M200_Diff.i3i", "Weapon\" & curItem2 & "/Cheytac_M200_Diff.i3i")
Dim be4 = UnicodeStringToBytes(be3)
My.Computer.FileSystem.WriteAllBytes(FileName, be4, True)
'System.IO.File.AppendAllText(FileName, be4)
' Dim fs As FileStream = New FileStream(oldfile, FileMode.Open)
' Dim br As BinaryReader = New BinaryReader(fs)
'Dim bin as byte[]= br.ReadBytes(Convert.ToInt32(fs.Length));
' fs.Close()
'br.Close()
End If
Catch ex As Exception
System.IO.File.AppendAllText("MathimaticalErrors.txt", ex.ToString)
End Try
End Sub
Public Function UnicodeBytesToString(ByVal bytes() As Byte) As String
Return System.Text.Encoding.Unicode.GetString(bytes)
End Function
Public Function UnicodeStringToBytes(ByVal str As String) As Byte()
Return System.Text.Encoding.Unicode.GetBytes(str)
End Function
The problem is that the newly created file is basically the same as the old file, and nothing has changed on it. How can I solve this?

At this point in your code:
Dim be2 As String = UnicodeBytesToString(be)
be2.Replace("Weapon\" & curItem & "/" & curItem & "_diff", "Weapon\" & curItem2 & "/" & curItem2 & "_diff")
The value in be2 would remain unchanged. You have to store the return value of Replace():
Dim be2 As String = UnicodeBytesToString(be)
be2 = be2.Replace("Weapon\" & curItem & "/" & curItem & "_diff", "Weapon\" & curItem2 & "/" & curItem2 & "_diff")
Also, at this line:
My.Computer.FileSystem.WriteAllBytes(FileName, be4, True)
The True at the end means you want to append the bytes. If the file is empty this will be fine. If not, then you'll end up adding the bytes to the end of the file each time. Not sure if that is your intended result...

Related

File can't be accessed because it's already in use

I have a Sub that reads a file that was created in another Sub. I'm getting an error
Can't access file in use in other process
From what I've read on the net I need to close the StreamReader. I've tried to use .close() on different variables, but nothing seems to work.
Below is the code that writes the file the other Sub then accesses.
Private Sub CreateGraphicsFunction(sender As Object, e As EventArgs)
Dim Regex = New Regex("infoEntityIdent=""(ICN.+?)[""].*?[>]")
strGraphicFile = MoveLocation & "\ICN-LIST.txt"
Dim ICNFiles = Directory.EnumerateFiles(MovePath, "*.*", SearchOption.AllDirectories)
For Each tFile In ICNFiles
Dim input = File.ReadAllText(tFile)
Dim match = Regex.Match(input)
If match.Success Then
output.Add(match.Groups(1).Value)
End If
Next
File.WriteAllLines(strGraphicFile, output)
locationGraphicsLog = strGraphicFile
End Sub
The other Sub that reads the file created
Private Sub btnFindICN_Click(sender As Object, e As EventArgs) Handles btnFindICN.Click
Application.UseWaitCursor = True
Application.DoEvents()
Me.Refresh()
Dim sGraphicFilesToFind As String
Dim graphicLocation As String
'MoveWithPath As String
Dim graphicFile As String
graphicLocation = txtSearchICN.Text
MoveLocation = MovePath
graphicLogFile = MoveLocation & "\Reports\1-OrphanedFilesItems.txt"
Dim FILE_NAME As String
FILE_NAME = MoveLocation & "\ICN-LIST.txt"
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Dim sGraphicFile As String
Do While objReader.Peek() <> -1
graphicFile = objReader.ReadLine()
sGraphicFilesToFind = graphicLocation & "\" & graphicFile & "*.*"
sGraphicFile = graphicFile
Dim createGraphicReportFldr As String
Dim paths() As String = IO.Directory.GetFiles(graphicLocation, sGraphicFile, IO.SearchOption.AllDirectories)
If paths.Count = 0 Then
'Debug.Print(graphicFile)
If System.IO.File.Exists(graphicLogFile) = True Then
Dim objWriter As New System.IO.StreamWriter(graphicLogFile, IO.FileMode.Append)
objWriter.WriteLine(graphicFile)
objWriter.Close()
Else
'MsgBox("Creating Orphaned graphicFile Now. ")
createGraphicReportFldr = MoveLocation & "\Reports"
If Not IO.Directory.Exists(createGraphicReportFldr) Then
IO.Directory.CreateDirectory(createGraphicReportFldr)
'MsgBox("folder created" & createGraphicReportFldr)
Dim writeFile As IO.StreamWriter
writeFile = IO.File.CreateText(graphicLogFile)
writeFile.Write(graphicFile & vbCrLf)
writeFile.Close()
Else
'MsgBox("Folder already exist")
End If
End If
Else
For Each pathAndFileName As String In paths
Dim createGraphicsFolder As String
'Dim moveFileToNewFolder As String
If System.IO.File.Exists(pathAndFileName) = True Then
Dim sRegLast As String = pathAndFileName.Substring(pathAndFileName.LastIndexOf("\") + 1)
Dim toGraphiicFileLocation As String
'MsgBox("sRegLast " & sRegLast)
fileGraphicLoc = MoveLocation & sRegLast
createGraphicsFolder = MoveLocation & "\Figures"
moveGraphicFileToNewFolder = MoveLocation & "\Figures\" & sRegLast
toGraphiicFileLocation = createGraphicsFolder & "\" & sRegLast
'MsgBox("FileLoc " & fileLoc)
If Not IO.Directory.Exists(createGraphicsFolder) Then
IO.Directory.CreateDirectory(createGraphicsFolder)
' MsgBox("folder created" & createGraphicsFolder)
End If
If System.IO.File.Exists(fileGraphicLoc) = False Then
System.IO.File.Copy(pathAndFileName, moveGraphicFileToNewFolder)
Debug.Write("Graphics moved to : " & moveGraphicFileToNewFolder & vbCrLf)
End If
End If
Next
End If
Loop
'MsgBox("graphicFiles have been moved")
Call CreateGraphicsFunction(Nothing, System.EventArgs.Empty)
Application.UseWaitCursor = False
Application.DoEvents()
' Me.Close()
End Sub
In the "other Sub", change
Dim objReader As New System.IO.StreamReader(FILE_NAME)
to
Using objReader = New System.IO.StreamReader(FILE_NAME)
and add End Using where you are done with it. Probably right after Loop. This will ensure that the disposable stream is always disposed.
See Using Statement (Visual Basic). You almost always want to wrap an IDisposable object in a Using block if you are able to restrict its scope to a single method.

Download multiple files from Web

I am working on some application to download files of stock prices for different dates from url. I am using the following code
Conn = New OdbcConnection("DSN=RA;MultipleActiveResultSets=True")
If Conn.State = ConnectionState.Closed Then
Conn.Open()
End If
Dim mont As Date
mont = DateTimePicker1.Value
Dim dnldurlA As String = "http://www.nseindia.com/content/historical/EQUITIES/"
Dim dnldurlB As String = UCase(mont.ToString("MMM"))
Dim dnldurlC As String = "/"
Dim dnldurlD As String = "cm"
Dim dnldurlE As String = mont.ToString("dd")
Dim dnldurlF As String = mont.ToString("yyyy")
Dim dnldurlG As String = "bhav"
Dim dnldurlH As String = ".csv"
Dim dnldurlI As String = ".zip"
Dim dnldurlJ As String = "\"
Dim FileName As String = dnldurlE & dnldurlB & dnldurlF & ".ZIP"
Try
Dim downloadClient As New WebClient()
downloadClient.Headers("Accept") = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"
downloadClient.Headers("User-Agent") = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.83 Safari/537.1"
Dim dnldurl As String = dnldurlA & dnldurlF & dnldurlC & dnldurlB & dnldurlC & dnldurlD & dnldurlE & dnldurlB & dnldurlF & dnldurlG & dnldurlH & dnldurlI
downloadClient.DownloadFile(New Uri(dnldurl), ("C:\" & FileName))
While (downloadClient.IsBusy = True)
End While
downloadClient.Dispose()
Catch ex As Exception
MsgBox("File can not be downloaded!!!")
Me.Close()
End Try
I am stuck with after downloading the first file, when I selected the file for another date, it throws an error
{"The remote server returned an error: (403) Forbidden."}
But when I exit the application and try again for the same date, the file is downloaded promptly.
Please help
Thanks in advance
Kris
I just made a small change and it worked perfectly
Conn = New OdbcConnection("DSN=RA;MultipleActiveResultSets=True")
If Conn.State = ConnectionState.Closed Then
Conn.Open()
End If
Dim mont As Date
mont = DateTimePicker1.Value
Dim dnldurlA As String = "http://www.nseindia.com/content/historical/EQUITIES/"
Dim dnldurlB As String = UCase(mont.ToString("MMM"))
Dim dnldurlC As String = "/"
Dim dnldurlD As String = "cm"
Dim dnldurlE As String = mont.ToString("dd")
Dim dnldurlF As String = mont.ToString("yyyy")
Dim dnldurlG As String = "bhav"
Dim dnldurlH As String = ".csv"
Dim dnldurlI As String = ".zip"
Dim dnldurlJ As String = "\"
Dim FileName As String = dnldurlE & dnldurlB & dnldurlF & ".ZIP"
Try
Dim downloadClient As New WebClient()
Dim dnldurl As String = dnldurlA & dnldurlF & dnldurlC & dnldurlB & dnldurlC & dnldurlD & dnldurlE & dnldurlB & dnldurlF & dnldurlG & dnldurlH & dnldurlI
downloadClient.DownloadFile(New Uri(dnldurl), ("C:\" & FileName))
While (downloadClient.IsBusy = True)
End While
downloadClient.Dispose()
Catch ex As Exception
MsgBox("File can not be downloaded!!!")
Me.Close()
End Try
Thanks

Update software function doesn't work if software is already open

I've a function that check update for my application. I've two mode for execute this function, in the first time that the application's start and in the tooltip menu. If I execute the software for the first time all working good, the update is found , but if I press on my button in the tooltip menu the same function (the exact function) not working. In particular the update is found but the software for download it (infinity blue) doesn't start.
This is the function:
Dim MyAppName As String = "Sund.exe"
Dim url As String = "www.site.com/update/" & "FileUpdates371.php"
Dim pageRequest As HttpWebRequest = CType(WebRequest.Create(url), HttpWebRequest)
Dim pageResponse As WebResponse = pageRequest.GetResponse()
Dim filelist As String : Dim Mainlist As String
Using r As New StreamReader(pageResponse.GetResponseStream())
filelist = r.ReadToEnd
If Not IO.File.Exists(Application.StartupPath & "\" & "Updates") Then
IO.File.WriteAllText(Application.StartupPath & "\" & "Updates", filelist)
End If
Dim sr As New StreamReader(Application.StartupPath & "\" & "Updates")
Mainlist = sr.ReadToEnd
Dim FileLines() As String = filelist.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
Dim MainLines() As String = Mainlist.Split(New String() {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
If Not Mainlist = filelist And Not FileLines.Length < MainLines.Length Then
Dim answer As DialogResult
answer = MessageBox.Show("Update available", "Update", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
If answer = vbYes Then
Dim App As New Process
App.StartInfo.FileName = Application.StartupPath & "\" & "InfinityBlue.exe"
App.StartInfo.Arguments = "Update|" & MyAppName & "|" & url
App.Start()
Me.Close()
End If
End If
End Using
If My.Computer.FileSystem.FileExists(Application.StartupPath & "\" & "InfinityBlueUpdate.exe") Then
My.Computer.FileSystem.DeleteFile(Application.StartupPath & "\" & "InfinityBlue.exe", FileIO.UIOption.OnlyErrorDialogs, FileIO.RecycleOption.DeletePermanently)
My.Computer.FileSystem.RenameFile(Application.StartupPath & "\" & "InfinityBlueUpdate.exe", "InfinityBlue.exe")
End If
I've also tried to catch the exception and there isn't exception. Why happean this?

VB file compression in VS2013

I came across an article on implementing .zip VB file compression in VS2013 but have a snag in implementing it.
When I get to the line System.IO.Compression.ZipFile.CreateFromDirectory, I get an error in VS that .ZipFile is not a member of ".Compression".
Here’s the code for my command button (using user3688529's code) called zipButton and listbox called filesListBox:
Private Sub zipButton_Click(sender As Object, e As EventArgs) Handles zipButton.Click
'Button click events.
'Start backup.
Dim PjtPath As String = TextBox1.Text
Dim ZipLocal As String = TextBox2.Text
Dim ZipNetwk As String = TextBox3.Text
Static Dim StartPath As String
Static Dim ZipPath As String
For Each a As String In filesListBox.SelectedItems()
'Dim PjtName As String = ListBox1.SelectedItems(a).ToString
Dim PjtName As String = a
Dim ZipExt As String = Format(Now, " yyyy-MM-dd # HHmm") & ".zip"
If TextBox2.Text = String.Empty Then
StartPath = PjtPath & "\" & PjtName
ZipPath = PjtPath & "\" & PjtName & ZipExt
ElseIf TextBox2.Text <> String.Empty Then
StartPath = PjtPath & "\" & PjtName
ZipPath = ZipLocal & "\" & PjtName & ZipExt
End If
System.IO.Compression.ZipFile.CreateFromDirectory _
(StartPath, ZipPath, IO.Compression.CompressionLevel.Optimal, True)
If TextBox3.Text <> String.Empty Then
Dim ZipCopy As String = ZipNetwk & "\" & PjtName & ZipExt
My.Computer.FileSystem.CopyFile(ZipPath, ZipCopy)
End If
Next
End Sub
Is there some module I need to include in order for the .ZipFle member to be accessable?
You probably need to add a reference to System.IO.Compression.FileSystem in your project references.
"Project -> Add Reference". Under Framework, find System.IO.Compression.FileSystem.

Read a text file which contains SQL code to create tables in a database

I need code to read a .txt file which is in my project bin\debug directory that contains SQL code to create tables in a large number it size of 936kb
This following code only I'm using...
By using this it gives result like table created but it is not reading the file... there is nothing in the database
Public Function readTextFile(ByVal fileName As String) As String
Dim strContent As String()
Dim x As String = ""
Try
'fileName = "CSYSS802.txt"
If Not System.IO.File.Exists(fileName) Then
'o Until EOF()
strContent = System.IO.File.ReadAllLines(fileName)
For Each Str As String In strContent
x = x + Str
Next
readTextFile = x
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
readTextFile = x
End Function
Public Sub createTable(ByVal vdbs As String, ByVal file As String)
username = frmlogin.txtusername.Text
password = frmlogin.txtusername.Text
vsvr = vServer
vdb = Trim$(vdbs)
strCon1 = "Server=" & vsvr & ";Database=" & vdb & ";uid=" & username & ";pwd=" & password & ";"
sqlCon1 = New SqlClient.SqlConnection(strCon1)
sqlCon1.Open()
Dim arr() As String
arr = Split(readTextFile(file), "GO")
Dim i As String
For Each i In arr
If i <> "" Then
Dim cmd2 As New SqlClient.SqlCommand("" & i & "")
cmd2.CommandType = CommandType.Text
cmd2.ExecuteNonQuery()
End If
Next
End Sub
In the readTextFile function, it will only attempt to read the text from the text file if the file DOESN'T exist. If the text file exists then the function returns an empty string and if the text file doesn't exist, the function will throw a file not found exception.
Replace:
If Not System.IO.File.Exists(fileName) Then
with:
If System.IO.File.Exists(fileName) = True Then
You might also want to include an Else clause in case the file doesn't exist as it won't throw an error since you have handled it correctly.
If System.IO.File.Exists(fileName) = True Then
strContent = System.IO.File.ReadAllLines(fileName)
For Each Str As String In strContent
x &= Str
Next
Return x
Else
MessageBox.Show("The file '" & fileName & "' does not exist.")
Return ""
End If
My Self I had Found The solution..I attache the Following Code...It now Creating All tables Properly..
Make sure that each Sql Commands in your Text File ends with go.. because i used "GO" Keyword to split the text...
Public Sub createTable(ByVal vdbs As String, ByVal file As String)
username = frmlogin.txtusername.Text
password = frmlogin.txtusername.Text
vsvr = vServer
vdb = Trim$(vdbs)
strCon1 = "Server=" & vsvr & ";Database=" & vdb & ";uid=" & username & ";pwd=" & password & ";"
sqlCon1 = New SqlClient.SqlConnection(strCon1)
sqlCon1.Open()
Dim arr() As String
arr = Split(readTextFile(file), " GO ")
Dim i As String
For Each i In arr
If i <> "" Then
Dim cmd2 As New SqlClient.SqlCommand("" & i & "", sqlCon1)
cmd2.CommandType = CommandType.Text
cmd2.ExecuteNonQuery()
End If
Next
End Sub
Public Function readTextFile(ByVal file As String) As String
Dim fso As New System.Object
Dim ts As Scripting.TextStream
Dim sLine As String
fso = CreateObject("Scripting.FileSystemObject")
ts = fso.openTextFile(file)
Do Until ts.AtEndOfStream
sLine = sLine & " " & ts.ReadLine
Loop
ts.Close()
fso = Nothing
readTextFile = sLine
End Function