What I'm trying to do:
Open two binary files, each 64 MB
Take first half of each byte of each file and combine those halves in 1 bytes same with second half, for example: first byte in first file is 0x51, in second file its 0xA2, so I need write two bytes in third file which are 0x5A and 0x12, same for whole bytes, therefore final length in third file will be 128 MB.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Try
' choosing first file
OpenFileDialog1.FileName = "First file"
OpenFileDialog1.Title = "Choose the Address.bin file"
OpenFileDialog1.Filter = "bin files (*.bin)|*.bin|All files
(*.*)|*.*"
If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK
Then
Label1.Text =
System.IO.Path.GetFullPath(OpenFileDialog1.FileName)
Else
Exit Sub
End If
Catch ex As Exception
End Try
Try ' choosing first file
OpenFileDialog1.FileName = "Second FIle"
OpenFileDialog1.Title = "Choose the Flash.bin file"
OpenFileDialog1.Filter = "bin files (*.bin)|*.bin|All files (*.*)|*.*"
If OpenFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK Then
Label2.Text = System.IO.Path.GetFullPath(OpenFileDialog1.FileName)
Else
Exit Sub
End If
Catch ex As Exception
End Try
Dim firstFileByte(1) As Byte
Dim SecondFileByte(1) As Byte
Dim Result As String
Dim Result2 As String
Dim Final(1) As Byte
For i = 0 To FileLen(Label1.Text) - 1
Using FirstFile As New FileStream(Label1.Text, FileMode.Open) 'save
'FIRST DIGIT********************************************************************************************
FirstFile.Seek(i, SeekOrigin.Begin)
FirstFile.Read(firstFileByte, 0, 1)
'TextBox1.Text = final(0).ToString("X")
Using SecFile As New FileStream(Label2.Text, FileMode.Open) 'save
SecFile.Seek(i, SeekOrigin.Begin)
SecFile.Read(SecondFileByte, 0, 1)
End Using
Result = firstFileByte(0).ToString("X2").Substring(0, 1) & SecondFileByte(0).ToString("X2").Substring(0, 1) ' comobining frist half of the first file and second file
Result2 = firstFileByte(0).ToString("X2").Substring(1, 1) & SecondFileByte(0).ToString("X2").Substring(1, 1) ' comobining second half of the first file and second file
End Using
Using vFs As New FileStream(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\Result.bin", FileMode.Append) ' save
TextBox1.Text = Result2
'Dim FileLenVar As UInt32 = FileLen(Environment.GetFolderPath(Environment.SpecialFolder.Desktop) & "\Result.bin") - 1
Final(0) = Convert.ToByte(Result, 16) 'converting result to the byte
Final(1) = Convert.ToByte(Result2, 16)
vFs.Write(Final, 0, 1)
vFs.Write(Final, 1, 1)
End Using
Next
End Sub
It works, but takes a lot of time: it writes 1 MB in 1 minute. How can I optimize it?
The files are small enough to load into RAM for processing. Processing the data in RAM can minimise the disk I/O needed, the latter very often being the slowest part of a program, especially if it is done in very small pieces like individual bytes. As also noted by Ben Voigt, string operations are somewhat slower than numeric operations.
Here's a simple demonstration of what could be done:
Imports System.IO
Module Module1
Dim f1 As String = "C:\temp\A.bin"
Dim f2 As String = "C:\temp\B.bin"
Dim outFile As String = "C:\temp\C.bin"
Sub CombineFiles()
Dim a1 = File.ReadAllBytes(f1)
Dim a2 = File.ReadAllBytes(f2)
Dim c(a1.Length + a2.Length - 1) As Byte ' c for combined
Dim highBits As Byte = &HF0
Dim lowBits As Byte = &HF
For i = 0 To c.Length - 1 Step 2
c(i) = a1(i \ 2) And highBits Or a2(i \ 2) >> 4
c(i + 1) = a1(i \ 2) << 4 Or a2(i \ 2) And lowBits
Next
File.WriteAllBytes(outFile, c)
End Sub
Sub CreateTestFiles()
'TODO: be more creative with the generated data.
Dim nBytes = 64
Dim a(nBytes - 1) As Byte
For i = 0 To nBytes - 1
a(i) = &H12
Next
File.WriteAllBytes(f1, a)
For i = 0 To nBytes - 1
a(i) = &HAB
Next
File.WriteAllBytes(f2, a)
End Sub
Sub Main()
'CreateTestFiles()
CombineFiles()
End Sub
End Module
Of course, you'd check that the input files were of equal length, and check for any other possible problems ;)
Related
I searched everywhere on stackoverflow.com but still not have a solution:
My code is very simple :
'Get Full Path of File
Dim elements As String = Path.GetTempPath() & "file.txt"
'Create A new folder for outputs if not exist
If (Not System.IO.Directory.Exists(Path.GetTempPath() & "folder")) Then
System.IO.Directory.CreateDirectory(Path.GetTempPath() & "folder")
End If
I want divide the file.txt with contents to (x) number of files inside the new folder
example :
if x = 3
the output files will be created automatically:
/folder/file_1.txt
/folder/file_2.txt
/folder/file_3.txt
Read the data from the existing text file.
Divide the data into an arbitrary number of strings of arbitrary length.
If the new directory doesn't exist create it.
Create files in this directory to store the arbitrary sections of data until an arbitrary number of files have been created and all data has been stored.
Since you refuse to provide the logic (I guess it is a secret), I will have to make some assumptions.
The original file contains lines that are approximately the same length.
The intent is divide the original file into files of approximately equal size.
The number of files is based on the size of the original file.
I split the files based on lines so a word would not be split between 2 files.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim OriginalFilePath = "C:/devlist.txt" '16KB file
Dim lines = File.ReadAllLines(OriginalFilePath)
Dim NumOfLines = lines.Length
Dim NumOfFiles As Integer = GetNumberOfFiles(OriginalFilePath, NumOfLines)
If NumOfFiles = -1 Then
MessageBox.Show("No data in file.")
Return
End If
'The "\" operator is integer division
Dim LinesPerFile = NumOfLines \ NumOfFiles
'Dim LeftoverLines = NumOfLines Mod NumOfFiles - didn't need this afterall
Directory.CreateDirectory("C:\Some Directory")
Dim StartIndex As Integer
Dim EndIndex As Integer
Dim sb As New StringBuilder
For i = 0 To NumOfFiles - 1
EndIndex = StartIndex + LinesPerFile
If EndIndex >= NumOfLines - 1 Then
EndIndex = NumOfLines - 1
End If
For index = StartIndex To EndIndex
sb.AppendLine(lines(index))
Next
Dim NewFilePath = $"C:\Some Directory\SplitFile{i.ToString}.txt"
'.WriteAllText will create the new file or overwrite it if it exists
File.WriteAllText(NewFilePath, sb.ToString)
StartIndex = EndIndex + 1
sb.Clear()
Next
End Sub
Private Function GetNumberOfFiles(FilePath As String, NumOfLines As Integer) As Integer
Dim OriginalFileLength = New FileInfo(FilePath).Length
Dim NumOfFiles As Integer
Select Case OriginalFileLength
Case 0
MessageBox.Show("No data in file")
Return -1
Case 1
NumOfFiles = 1
Case 2
If NumOfLines < 2 Then
NumOfFiles = 1
End If
NumOfFiles = 2
Case 3 To 10_000
If NumOfLines < 3 Then
NumOfFiles = NumOfLines
Else
NumOfFiles = 3
End If
'You can continue the If statements but I assumed
'a file of this size would have at least 4 lines
Case 10_001 To 100_000
NumOfFiles = 4
Case 100_001 To 500_000
NumOfFiles = 5
Case Else
NumOfFiles = 6
End Select
Return NumOfFiles
End Function
Result of splitting the 16KB file
This just sample
Dim Divider = 3
Dim myNewFile(Divider - 1) As String
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText("C:\test.txt")
Dim myNewSize As Long = 0
Long.TryParse(fileReader.Length / Divider, myNewSize)
If myNewSize = 0 Then
MessageBox.Show("Can't Be Processed")
Exit Sub
End If
For myCnt As Int16 = 0 To divider - 1
myNewFile(myCnt) = fileReader.Substring(myCnt * myNewSize + 1, myNewSize)
Next
'Resize The Last For Include The Remain
Dim myNewLastSize As Long = myNewSize + fileReader.Length - myNewSize * Divider
myNewFile(Divider - 1) = fileReader.Substring((Divider - 1) * myNewSize + 1, myNewLastSize)
And then you should save each split data to each it's table
I am making a test program to let the user select a folder from a tree view which will show the drives and folders (when expanded) and the files that are present in the selected folder will be displayed in the listview.
The problem i am facing with the listview is that, there is a extra space added before the file icon of every file.
And i am also getting duplicate folder entries when expanded in the treeview.
the icon size of imageListListView is 24x24
Public Class FolderTreeStructure
Private Sub FolderTreeStructre_Load(sender As Object, e As EventArgs) Handles MyBase.Load
'add drive list in treeview
Dim drives() As String = System.IO.Directory.GetLogicalDrives()
For Each drive In drives
TreeView1.Nodes.Add(drive)
Next
'add folder present in each drives
Dim folders() As String
Dim j As Integer = 0
For i As Integer = 0 To TreeView1.Nodes.Count - 1
Try
folders = IO.Directory.GetDirectories(TreeView1.Nodes.Item(i).Text)
For Each folder In folders
TreeView1.Nodes.Item(i).Nodes.Add(folder)
TreeView1.Nodes.Item(i).Nodes.Item(j).ImageIndex = 1
j += 1
Next
j = 0
Catch
Continue For
End Try
Next
End Sub
Private Sub TreeView1_AfterExpand(sender As Object, e As TreeViewEventArgs) Handles TreeView1.AfterExpand
Me.Cursor = Cursors.WaitCursor
Dim folders() As String
Dim j As Integer = 0
TreeView1.BeginUpdate()
For i As Integer = 0 To e.Node.Nodes.Count - 1
Try
folders = IO.Directory.GetDirectories(e.Node.Nodes.Item(i).Text)
For Each folder In folders
e.Node.Nodes.Item(i).Nodes.Add(folder)
e.Node.Nodes.Item(i).Nodes.Item(j).ImageIndex = 1
j += 1
Next
j = 0
Catch
Continue For
End Try
Next
TreeView1.EndUpdate()
Me.Cursor = Cursors.Default
End Sub
Private Sub TreeView1_AfterSelect(sender As Object, e As TreeViewEventArgs) Handles TreeView1.AfterSelect
addFolderItems(e.Node.Text)
End Sub
Public Sub addFolderItems(ByVal path As String)
Try
ListView1.Items.Clear()
Dim files() As String = IO.Directory.GetFiles(path)
Dim fileCount As Integer = files.Length
Dim fileInfo As IO.FileInfo
Dim i As Integer = 0
Dim Items = ListView1.Items
'different file sizes
Dim fileSize As Long
Dim kb As Double
Dim mb As Double
Dim gb As Double
'for extracting file type description
Dim Clskey As Microsoft.Win32.RegistryKey = Microsoft.Win32.Registry.ClassesRoot
Dim ExtKey As Microsoft.Win32.RegistryKey
Dim Appkey2 As Microsoft.Win32.RegistryKey
Dim AppDesc As String
'to hold file icon
Dim iconForFile As Icon = SystemIcons.WinLogo
ListView1.BeginUpdate()
For Each file In files
Try
fileInfo = New IO.FileInfo(file)
'adds item number
Items.Add(Items.Count + 1)
'adds file name
Items.Item(i).SubItems.Add(fileInfo.Name)
' Check to see if the image collection contains an image
' for this extension, using the extension as a key.
If Not (ImageListListView.Images.ContainsKey(fileInfo.Extension)) Then
' If not, add the image to the image list.
iconForFile = System.Drawing.Icon.ExtractAssociatedIcon(fileInfo.FullName)
ImageListListView.Images.Add(fileInfo.Extension, iconForFile)
End If
Items.Item(i).ImageKey = fileInfo.Extension
'adds file size
fileSize = fileInfo.Length
If fileSize > 1024 Then
kb = fileSize / 1024
If kb > 1024 Then
mb = kb / 1024
If mb > 1024 Then
gb = mb / 1024
Items.Item(i).SubItems.Add(Format(gb, "0.00") & " GB")
Else
Items.Item(i).SubItems.Add(Format(mb, "0.00") & " MB")
End If
Else
Items.Item(i).SubItems.Add(Format(kb, "0.00") & " KB")
End If
Else
Items.Item(i).SubItems.Add(fileSize.ToString & " bytes")
End If
'adds file extension without .
If fileInfo.Extension.Length > 0 Then
Items.Item(i).SubItems.Add(fileInfo.Extension.Substring(1))
Else
Items.Item(i).SubItems.Add(fileInfo.Extension)
End If
'adds date modified
Items.Item(i).SubItems.Add(fileInfo.LastWriteTime.ToString)
'extract file type description from registry
ExtKey = Clskey.OpenSubKey(fileInfo.Extension, False)
If ExtKey IsNot Nothing Then 'Occurs nullreff when extension not found
AppDesc = ExtKey.GetValue("", "")
Appkey2 = Clskey.OpenSubKey(AppDesc)
Items.Item(i).SubItems.Add(Appkey2.GetValue("", ""))
End If
i += 1
Catch
Continue For
End Try
Next
ListView1.EndUpdate()
Catch e As Exception
MsgBox(e.ToString)
End Try
End Sub
End Class
Link for image
http://i.imgur.com/GLS0ZiO.png
I want to generate a single SHA256 hash of all the files in a folder in visual basic. I have tried the following code but it generates individual hashes of all files inside the folder, but not a single hash. Can anybody please help.
Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
Dim directory As String
If TextBox2.Text.Length < 1 Then
Dim fdb As New FolderBrowserDialog
Dim dr As DialogResult = fdb.ShowDialog()
If (dr = DialogResult.OK) Then
directory = fdb.SelectedPath
Else
MsgBox("No directory selected")
Return
End If
Else
directory = TextBox2.Text
End If
Try
' Create a DirectoryInfo object representing the specified directory.
Dim dir As New DirectoryInfo(directory)
' Get the FileInfo objects for every file in the directory.
Dim files As FileInfo() = dir.GetFiles()
' Initialize a SHA256 hash object.
Dim mySHA256 As SHA256 = SHA256Managed.Create()
Dim hashValue() As Byte
' Compute and print the hash values for each file in directory.
Dim fInfo As FileInfo
For Each fInfo In files
' Create a fileStream for the file.
Dim fileStream As FileStream = fInfo.Open(FileMode.Open)
' Be sure it's positioned to the beginning of the stream.
fileStream.Position = 0
' Compute the hash of the fileStream.
hashValue = mySHA256.ComputeHash(fileStream)
' Write the name of the file to the Console.
MsgBox(fInfo.Name + ": ")
' Write the hash value to the Console.
PrintByteArray(hashValue)
' Close the file.
fileStream.Close()
Next fInfo
Return
Catch DExc As DirectoryNotFoundException
MsgBox("Error: The directory specified could not be found.")
Catch IOExc As IOException
MsgBox("Error: A file in the directory could not be accessed.")
End Try
End Sub
Public Function PrintByteArray(ByVal array() As Byte)
Dim i As Integer
For i = 0 To array.Length - 1
Label3.Text = (String.Format("{0:X2}", array(i)))
If i Mod 4 = 3 Then
Label3.Text = (" ")
End If
Next i
Return Label3.Text
End Function 'PrintByteArray
You can combine the hashes with XOR to give one 256-bit hash (32 bytes). Because XOR is associative (A XOR B = B XOR A), it does not matter in which order you XOR the file hashes together. You will have to XOR the individual bytes of each hash: Most efficient way to xor byte array in vb.net.
I use VB.net 2008 to make a memory scanner and hacking program. I try some of their answers but still the memory scanner is slow. Maybe I have an improvement because before I scan a simple minesweeper and it takes 10 to 20 minutes. But now I can scan it for 2 to 10 seconds.
But I'm still not satisfied because when I try it in other games it takes 5 to 10 minutes or sometimes freeze due of too much long and too much usage of CPU.
Here is my code
Assume I declare all the API and some arguments for making a first scan
this code is a sample of scanning a 4 bytes address:
'' Command Button Event
btn_firstScan(....) Handle....
'' The Code
Me.Enabled = False
FirstScanThread = New Thread(AddressOf scanF)
FirstScanThread.IsBackground = True
FirstScanThread.Priority = ThreadPriority.Highest
FirstScanThread.Start() '' Thread Started for the First Scan.
End sub
Private Sub scanF() '' This is the Function is being Executed by the FirstScanThread at the btn_firstScan.
FirstScan(Of Int32)(pHandle, &H400000, &H7FFF0000, CType(txt_value.Text, Int32))
End Sub
The Sub FirstScan Executed by Sub scanF() that is being Executed by FirstScanThread in Command button btn_firstScan sub
Friend Sub FirstScan(Of T)(ByVal pHandle As IntPtr, ByVal minAddress As Int64, ByVal maxAddress As Int64, _
ByVal VALUE As T, Optional ByVal tempFileName As String = "temp.txt")
Dim thr As New Thread(AddressOf getProcessMemoryInfo) '' Get the Process Memory Info First
Dim memRange As New scanRange
memRange.minimum_address = minAddress
memRange.maximum_address = maxAddress
thr.IsBackground = True
thr.Priority = ThreadPriority.Highest
thr.Start(memRange)
thr.Join()
thr = New Thread(AddressOf dumpReadProcessMemory) '' Read All Bytes and Dump to the Temporary File
thr.IsBackground = True
thr.Priority = ThreadPriority.Highest
thr.Start()
thr.Join()
thr = New Thread(AddressOf readTempFile) '' Scan the Dump File in a Specific Set of Bytes [4 Bytes Aligned]
thr.IsBackground = True
thr.Priority = ThreadPriority.Highest
thr.Start(VALUE)
thr.Join()
setControlState(Me, True) '' If the Scan is Complete , The form is Ready Again to Receive Input
End Sub
Friend Sub dumpReadProcessMemory() '' This Sub is Use to Dump the All Bytes Read by ReadProcessMemory
Dim INFO As FileStream = New FileStream("FIRST.INFO.txt", FileMode.Open, FileAccess.Read, FileShare.Read)
Dim SR As StreamReader = New StreamReader(INFO) '' This is use to Obtain the Info that is needed to switch Page by Page Faster , No need to obtain in VirtualQueryEx
Dim BFILE As FileStream = New FileStream("FIRST.SCAN.txt", FileMode.Create, FileAccess.Write, FileShare.Write)
Dim BW As BinaryWriter = New BinaryWriter(BFILE) '' This is the Binary Writer for writing the READ Bytes
Dim BUFFER(0 To (1048576 * 128)) As Byte
Dim mem As New memoryInfo
While Not SR.EndOfStream '' While there is Page Found
mem.regionBaseAddress = CLng(SR.ReadLine.ToString)
mem.regionSize = CLng(SR.ReadLine.ToString)
ReadProcessMemory(pHandle, mem.regionBaseAddress, BUFFER, mem.regionSize, 0)
BW.Write(BUFFER, 0, mem.regionSize)
Thread.Sleep(1)
End While
SR.Close()
SR.Dispose()
INFO.Close()
INFO.Dispose()
BW.Close()
BFILE.Close()
BFILE.Dispose()
GC.Collect() '' Collect Garbage of BUFFER prevent CPU Stressing and RAM Leak, and i think i helps :P
End Sub
Friend Sub getProcessMemoryInfo(ByVal Obj As Object) '' Use to Get What PAGE is Readable/Writable and its Size
Dim FILE As System.IO.FileStream = New System.IO.FileStream("FIRST.INFO.txt", IO.FileMode.Create, FileAccess.Write, IO.FileShare.Write)
Dim SW As System.IO.StreamWriter = New System.IO.StreamWriter(FILE)
Dim BASE_ADDRESS As Int64 = CLng(Obj.minimum_address.ToString)
Dim MAX As Int64 = CLng(Obj.maximum_address.ToString)
Dim PAGE_COUNT As Integer = 0
While VirtualQueryEx(pHandle, BASE_ADDRESS, MBI, MBIsize)
If MBI.State = MemoryAllocationState.Commit Then
If MBI.zType = MemoryAllocationType.MEM_PRIVATE Or MBI.zType = MemoryAllocationType.MEM_IMAGE Then
Select Case MBI.AllocationProtect
'' Check if The Region is Readable/Writable and Executable
Case MemoryAllocationProtectionType.PAGE_CANWRITE
GoTo WRITE_INFO
Case MemoryAllocationProtectionType.PAGE_EXECUTE_READWRITE
GoTo WRITE_INFO
Case MemoryAllocationProtectionType.PAGE_WRITECOMBINE
GoTo WRITE_INFO
Case MemoryAllocationProtectionType.PAGE_EXECUTE_WRITECOPY
GoTo WRITE_INFO
Case MemoryAllocationProtectionType.PAGE_READWRITE
GoTo WRITE_INFO
Case Else
GoTo BYPASS_WRITE
End Select
WRITE_INFO:
SW.WriteLine(BASE_ADDRESS)
SW.WriteLine(MBI.RegionSize.ToInt32)
Thread.Sleep(1)
'PAGE_COUNT += 1
End If
End If
BYPASS_WRITE:
BASE_ADDRESS = BASE_ADDRESS + MBI.RegionSize.ToInt32
updateProgressTo(Me.pb_scanProgress, CInt(BASE_ADDRESS / MAX * 100))
End While
SW.Close()
SW.Dispose()
FILE.Close()
FILE.Close()
'Console.WriteLine(PAGE_COUNT)
End Sub
Public Sub readTempFile(ByVal Value As Object)
Dim TEMP As System.IO.FileStream = New System.IO.FileStream("TEMP.txt", IO.FileMode.Create, IO.FileAccess.Write, IO.FileShare.Write)
Dim TFILE As System.IO.FileStream = New System.IO.FileStream("FIRST.INFO.txt", IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Dim BFILE As System.IO.FileStream = New System.IO.FileStream("FIRST.SCAN.txt", IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.Read)
Dim SW As System.IO.StreamWriter = New System.IO.StreamWriter(TEMP) '' Will Contain a list of Addressed found with the Value input.
Dim SR As System.IO.StreamReader = New System.IO.StreamReader(TFILE) '' Contains the Region baseAddesses and Size
Dim BR As System.IO.BinaryReader = New System.IO.BinaryReader(BFILE) '' Contains the Bytes being Dump Before and will now Read for Scanning.
Dim ADDRESS_POINTER As Int64 = 0
Dim mem As New memoryInfo
Dim TEMP_BYTE(0 To 4 - 1) As Byte
Dim BUFFER(0 To (1024 * 1024)) As Byte = 1024KB
Dim BUFFER_INDEX = 0
mem.regionBaseAddress = CLng(SR.ReadLine.ToString) ''Obtain the Staring Base Address
mem.regionSize = CLng(SR.ReadLine.ToString) '' Obtain the Region Size
ADDRESS_POINTER = mem.regionBaseAddress
While BR.Read(BUFFER, 0, BUFFER.Length) '' Fill the BUFFER with Data
BUFFER_INDEX = 0
While BUFFER_INDEX < BUFFER.Length - (4 - 1)
For a As Integer = 0 To (4 - 1) '' Compile the Read Bytes
TEMP_BYTE(a) = BUFFER(BUFFER_INDEX + a)
Next
If BitConverter.ToInt32(TEMP_BYTE, 0) = Value Then '' If the Compiled 4 Bytes = Value then
SW.WriteLine(formatHex(Hex(ADDRESS_POINTER).ToString))
'addItemTo(Me.lb_addressList, formatHex(Hex(ADDRESS_POINTER).ToString))
End If
ADDRESS_POINTER += 4
BUFFER_INDEX += 1
mem.regionSize -= 4
If mem.regionSize <= 0 Then
If SR.EndOfStream Then
Exit While
Else
''Switch to the Next Region
mem.regionBaseAddress = CLng(SR.ReadLine.ToString) ''Obtain the Staring Base Address
mem.regionSize = CLng(SR.ReadLine.ToString) '' Obtain the Region Size
ADDRESS_POINTER = mem.regionBaseAddress
End If
End If
End While
Thread.Sleep(1) '' Prevent 100% CPU Usage therefore the Form and other App avoid Crashing and Not Responding,
End While
BR.Close()
BFILE.Close()
SW.Close()
TEMP.Close()
SW.Dispose()
TEMP.Dispose()
SR.Close()
SR.Dispose()
TFILE.Dispose()
GC.Collect()
setControlState(Me, True) '' Make the Form Enabled
End Sub
NOTE: formatHex is only a Function that will put trailing Zeros in the front of Hex String if the Hex is not have Length of 8.
This code works in minesweeper in Windows XP 32 Bit and works fast in MINESWEEPER ONLY. I tried it in Grand Chase and Farm Frenzy; the scan won't ends because its still slow and even the scan is done, there is no address being found (maybe because in just tested it for 4 bytes).
I like to use VirtualProtectEx and VirtualAllocEx to enable to scan those PAGE_GUARD and write on it. Therefore I am able to obtain the specific address that I want but I can't do it because it is still slow. I make the PAGE_GUARD'ed PAGE into EXECUTE_READWRITE it will make more bytes to scan. It will make the App slower.
I am trying to convert VB5 to .NET and cannot get a binary read to work. My VB.NET decode only reads the first two characters correctly.
The (VB5->VB.NET) encode is
' Open file
x = Rnd(-mKeyValue)
filenum = FreeFile()
Try
FileOpen(filenum, Filename, OpenMode.Binary)
Catch ex As IO.IOException
MsgBox(ex.ToString, MsgBoxStyle.Critical, "File opening error")
Exit Sub
End Try
' write data
filecontents = ""
For i = 1 To Len(stringdate)
charnum = Asc(Mid(stringdate, i, 1))
randomint = Int(256 * Rnd())
charnum = charnum Xor randomint
singlechar = Chr(charnum)
FilePut(filenum, singlechar, i)
filecontents = filecontents & singlechar
Next i
And the (VB5->VB.NET) decode is
x = Rnd(-mKeyValue)
filenum = FreeFile()
FileOpen(filenum, Filename, OpenMode.Binary)
For i = 1 To LOF(filenum)
'To VB.NET
FileGet(filenum, singlechar, i)
charnum = Asc(singlechar)
Debug.Print("VB5 singlechar = " & singlechar)
randomint = Int(256 * Rnd())
charnum = charnum Xor randomint
singlechar = Chr(charnum)
Next i
My VB.NET code which fails (cannot read the file correctly) is;
Using reader As New BinaryReader(File.Open(Filename, FileMode.Open))
' Loop through length of file.
Dim pos As Integer = 0
Dim length As Integer = reader.BaseStream.Length
While pos < length
' Read the integer.
singlechar = reader.ReadChar()
charnum = Asc(singlechar) 'singlechar is type Char
randomint = Int(256 * Rnd())
charnum = charnum Xor randomint
singlechar = Chr(charnum)
i += 1
End While
End Using
Can anyone help me with translation from VB5 to .NET?
In VB.Net everything is a bit shorter ;)
' get a string from an encrypted file file:
Dim b() As Byte = IO.File.ReadAllBytes("path")
For i = 0 To b.Length - 1
b(i) = b(i) Xor (256 * Rnd())
Next
Dim s As String = System.Text.Encoding.ASCII.GetString(b)
Why read byte by byte (no sense to read 'char' anyway, since you only want the 8bit ASCII code), when .Net can read it at once? Your file is not larger > 100 MB, I assume? Then after getting the array, you simply XOR each element with your "random" value. If you dont need to be compatible to old versions, you might better use Random. Or maybe even better ... USE REAL ENCRYPTION (in .Net it's built-in!)
' put a string into a file
Dim c() As Byte = System.Text.Encoding.ASCII.GetBytes("The String you want to store encrypted")
For i = 0 To c.Length - 1
c(i) = c(i) Xor (256 * Rnd())
Next
IO.File.WriteAllBytes("another path", c)
Same for "encrypting". Convert the string to an array of byte (=ASCII values), XOR it and then write it back in ONE operation.
See the dangers of Unicode:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
' Beware of UNICODE ... !!!
Using sw As New FileStream("foo.foo", FileMode.OpenOrCreate, FileAccess.Write)
' with old VB you effectively wrote BYTE data
sw.Write({65, 192}, 0, 2)
End Using
Using br As New BinaryReader(File.Open("foo.foo", FileMode.Open, FileAccess.Read))
' You are telling. Net that you expect a CHAR, which is not ASCII, but UNICODE
Dim c As Char = br.ReadChar
Dim d As Char = br.ReadChar
Dim cc = Asc(c)
Dim dd = Asc(d)
Debug.Print("65 -> {0}, 192 -> {1}", cc, dd)
End Using
End Sub
The output is 65 -> 65, 192 -> 63