resource file in VB.NET - vb.net

How can I use a .exe file in my resources folder? I want to copy the file in the resource folder to another folder.
tried this
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If (Directory.Exists("Files")) Then
Else
End If
Directory.CreateDirectory("Files")
Dim FileToCopy As String
Dim NewCopy As String
FileToCopy = My.Resources.THEFILEIWANT <- only this part doesn't work
NewCopy = "Files\THEFILEIWANT.exe"
If System.IO.File.Exists(FileToCopy) = True Then
System.IO.File.Copy(FileToCopy, NewCopy)
End If
End Sub
This is needed so when ther file doesn't exists the file gets created/copied.
Does anyone knows how I can call the file from the resource folder?
Tried this ` Dim writePermission As FileIOPermission
writePermission = New FileIOPermission(FileIOPermissionAccess.Write)
If (SecurityManager.IsGranted(writePermission)) Then
My.Computer.FileSystem.WriteAllBytes("Files", My.Resources.unscrambler, False)
End If`
But I'm getting a invalid permission error.

I am still a beginner but I could suggest using a packer, such as the one included with CodePlex's Confuser. It packs multiple assemblies into one (as do all packers), and obviously, Confuser offers obfuscation, and is Free.
*One warning!* Packers have been known to raise alerts in Anti-virus software, so check your app with different AV software.
Hope this info is useful. :)

Related

visual studio 2019 how do I know what References to import and path settings

I created a Visual Studio 2019 project that uses FileSystem.FileExists and both StreamWriter and StreamReader
I also created a folder named Resource with the intention of creating a txt file in this folder
Knowing I need to tell the Writer and Reader where to find the file I used these lines of code
Dim path As String = "C:/Users/Me/source/repos/TestForms/TestForms/Resource/"
If Not My.Computer.FileSystem.FileExists(path & "Check.txt") Then
Because I do not full understand how to deal with a SQLite database yet lets say I put the database in the folder Resource. And if I make a EXE package that will run on another computer that string path is by my best guess is not going to work
In the process of leaning I keep seeing this line of code. I see no path to the database
m_dbConnection = New SQLiteConnection("Data Source=MyDatabase.sqlite; Version=3;")
Granted I am dealing with a txt file now but if it was a SQLite database file
My Question is how does the connection know where the database is ?
I also need to import this reference Imports System.IO
Coming from NetBeans I got spoiled with Auto Import
Second Question Does VS 2019 not have an Auto Import feature?
I am adding a screen shot of Solution Explore
Tried to add Resource folder to Resources that did not work real well
Stream Reader Code below without error
Private Sub btnRead_Click(sender As Object, e As EventArgs) Handles btnRead.Click
readDATA()
End Sub
Private Sub readDATA()
Dim line As String
Using reader As New StreamReader(path & "Check.txt", True)
line = reader.ReadToEnd.Trim
tbHaveOne.Text = line
End Using
End Sub
Code that creates Check.txt
Private Sub frmThree_Load(sender As Object, e As EventArgs) Handles MyBase.Load
haveFILE()
'tbHaveTwo.Text = frmOne.vR'KEEP see frmOne
'tbHaveOne.Select()
End Sub
Public Sub haveFILE()
'If My.Computer.FileSystem.FileExists(path & "Check.txt") Then
' MsgBox("File found.")
'Else
' MsgBox("File not found.")
'End If
If Not My.Computer.FileSystem.FileExists(path & "Check.txt") Then
' Create or overwrite the file.
Dim fs As FileStream = File.Create(path & "Check.txt")
fs.Close()
tbHaveTwo.Text = "File Created"
tbHaveOne.Select()
Else
tbHaveTwo.Text = "File Found"
tbHaveOne.Select()
End If
End Sub
You should pretty much never be hard-coding absolute paths. If you want to refer to a path under the program folder then you use Application.StartupPath as the root and a relative path, e.g.
Dim filePath = Path.Combine(Application.StartupPath, "Resource\Check.txt")
Then it doesn't matter where you run your program from. For other standard folder paths, you should use Environment.GetFolderPath or My.Computer.FileSystem.SpecialDirectories. For non-standard paths, you should let the user choose with a FolderBrowserDialog, OpenFileDialog or SaveFileDialog and then, if appropriate, save that path to a setting or the like.
When it comes to database connection strings, some ADO.NET providers support the use of "|DataDirectory|" in the path of a data file and that gets replaced at run time. What it gets replaced with depends on the type of app and how it was deployed. For Web Forms apps, it resolves to the App_Data folder. For ClickOnce Windows apps it resolves to a dedicated data folder. For other Windows apps, it resolves to the program folder, just like Application.StartupPath. I think the SQLite provider supports it but I'm not 100% sure. If it does, you could use something like this:
m_dbConnection = New SQLiteConnection("Data Source=|DataDirectory|\Resource\MyDatabase.sqlite; Version=3;")
EDIT:
If you add data files to your project in the Solution Explorer and you want those to be part of the deployed application then you need to configure them to make that happen. Select the file in the Solution Explorer and then set the Build Action to Content and the Copy to Output Directory property to Copy Always or, if you intend to make changes to the file when the app is running, Copy if Newer.
When you build, that file will then be copied from your project source folder to the output folder along with the EXE. You can then access it using Application.StartupPath at run time. That means while debugging as well as after deployment, because it will be copied to the "\bin\Release" output folder as well as the "\bin\Debug" output folder. If you add the file to a folder in the Solution Explorer, that file will be copied to, hence the reason I said earlier to use this:
Dim filePath = Path.Combine(Application.StartupPath, "Resource\Check.txt")
Here is the working code to Create a Text file if it does not exist and if it does exist the user is notified.
We also were able to Write & Read from the Text file
One of the disappointments is we were not able to use StreamReader
We did solve this error where the file name was created like this "Check.txtCheck.txt This line of code below created the File this way in the folder Bin > Debug
If Not My.Computer.FileSystem.FileExists(filePath & "Check.txt") Then See Code for correct format
One other BIG lesson Do NOT create a folder and place your Text file in that folder
I am not sure using the code "Using" was a good idea further research needed on that issue
Working Code Below
Private Sub frmThree_Load(sender As Object, e As EventArgs) Handles MyBase.Load
haveFILE()
End Sub
Public Sub haveFILE()
If Not System.IO.File.Exists(filePath) Then
System.IO.File.Create(filePath).Dispose()
tbHaveTwo.Text = "File Created"
tbHaveOne.Select()
Else
My.Computer.FileSystem.FileExists(filePath) ' Then
tbHaveTwo.Text = "File Found"
tbHaveOne.Select()
End If
'This line of code created the File this was in the Bin > Debug folder Check.txtCheck.txt
'If Not My.Computer.FileSystem.FileExists(filePath & "Check.txt") Then
End Sub
Sub PlaySystemSound()
My.Computer.Audio.PlaySystemSound(
System.Media.SystemSounds.Hand)
End Sub
Private Sub btnWrite_Click(sender As Object, e As EventArgs) Handles btnWrite.Click
If tbHaveOne.Text = "" Then
PlaySystemSound()
'MsgBox("Please enter a username.", vbOKOnly, "Required Data")
'If MsgBoxResult.Ok Then
' Return
'End If
Const Title As String = "To EXIT Click OK"
Const Style = vbQuestion
Const Msg As String = "Enter Data" + vbCrLf + vbNewLine + "Then Write Data"
Dim result = MsgBox(Msg, Style, Title)
If result = vbOK Then
'MsgBox("Enter Data")
tbHaveOne.Select()
Return
End If
End If
writeDATA()
End Sub
Private Sub writeDATA()
Dim file As System.IO.StreamWriter
file = My.Computer.FileSystem.OpenTextFileWriter(filePath, True)
file.WriteLine(tbHaveOne.Text)
file.Close()
tbHaveOne.Clear()
tbHaveTwo.Text = "Data Written"
End Sub
Private Sub btnRead_Click(sender As Object, e As EventArgs) Handles btnRead.Click
readDATA()
End Sub
Public Sub readDATA()
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(filePath)
tbHaveOne.Text = fileReader
End Sub

Download, get the filename and execute the file

I am posting here to ask you for help, thank you first of all for reading my message and being able to help me. :)
So here's the problem, I have a little program that I'm creating, in this one, I integrated a button that normally allows to download a tool to run it.
However the link of the file does not point directly in .exe it is a link like this one :
mydomain.com/file/file48.php
The problem is that I manage to get the file, but this one is named file48.php and gets the extension of a php file, what I would like is to get the original name of the downloaded .exe file in order to be able to execute it within my application.
Here is the current code I'm using :
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim client As New WebClient
AddHandler client.DownloadFileCompleted, AddressOf client_DownloadFileCompleted
client.DownloadFileAsync(New Uri("https ://mydomain.com/files/index.php"), fileName, filename)
End Sub
Private Sub client_DownloadFileCompleted(sender As Object, e As AsyncCompletedEventArgs)
Dim client = DirectCast(sender, WebClient)
client.Dispose()
Dim filename As String = CType(e.UserState, String)
End Sub
Thanks a lot for your help, I've been searching for hours without much success...

The system cannot find the reference specified for an assembly

I have a VB.NET solution which have a few projects and a 'References' folder in the root directory.
Now I want to add a new dll reference to one of the projects from this References folder but getting the following message:
The system cannot find the reference specified
How can this be solved?
I encountered this many times. Here I was trying to execute a jar file when a picturebox was clicked. I added my jar to my resources :
Private Sub PictureBox9_Click(sender As Object, e As System.EventArgs) Handles _PictureBox9.Click
Dim dir As String = My.Computer.FileSystem.SpecialDirectories.Temp
Dim filename As String = dir + "minecraft.jar" 'Look Below
IO.File.WriteAllBytes(filename, My.Resources.minecraft)
Process.Start(My.Computer.FileSystem.SpecialDirectories.Temp & "minecraft.jar")
End Sub
The following worked for other programs though, but not minecraft, :
Private Sub Panel9_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Panel9.Click
proc = Process.Start("vbexpress.exe", "")
End Sub
*proc was a New System.Diagnostics.Process()
But for actual files, you have manually lure them out of their location.
So I did Me.Resources.1234.png which saved me writing the directory. But this still did not work with minecraft, so I kept that long paragraph about in place.

VB 2010 mkdir read only

Hi i cant seem to get mkdir to create a folder which isnt read only, this is causing alot of problems in my code because i am unable to write files to the directory i have created. thanks for any help. this is my code below:
Else
MessageBox.Show("Please set a Root Path for your ****")
RootFBD.ShowDialog()
TextBox1.Text = RootFBD.SelectedPath
My.Computer.FileSystem.CreateDirectory("C:\****-Tools\config\root.txt")
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim f2 As New FileIOPermission(FileIOPermissionAccess.Read, TextBox1.Text)
f2.AddPathList(FileIOPermissionAccess.Write Or FileIOPermissionAccess.Read, TextBox1.Text)
Dim rootSave As System.IO.StreamWriter
rootSave = My.Computer.FileSystem.OpenTextFileWriter("C:\****-Tools\config\root.txt", True)
rootSave.WriteLine(TextBox1.Text)
Me.Hide()
MainTool.Show()
End Sub
End Class
Thanks again josh
You're misunderstanding the problem; this isn't a permission issue.
Rather, you're leaving the file open, which prevents other processes from writing to ir.
You just need to Close() your StreamWriter.
Or, you can just call File.AppendText, which will avoid the issue.
You are creating the directory with the file name. Try this:
My.Computer.FileSystem.CreateDirectory("C:\****-Tools\config")

What is the file path, as a string, of a file in the application's resources?

The reason I ask is that I want to print, at run-time, a file in the application's resources, like this:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim printProcess As New Process
printProcess.StartInfo.CreateNoWindow = True
printProcess.StartInfo.FileName = "C:\Users\Geoffrey van Wyk\Documents\Countdown_Timer_Help.rtf"
printProcess.StartInfo.FileName = My.Resources.Countdown_Timer_Help
printProcess.StartInfo.Verb = "Print"
printProcess.Start()
End Sub
When I use "C:\Users\Geoffrey van Wyk\Documents\Countdown_Timer_Help.rtf" as the argument of FileName, it works. But when I use My.Resources.Countdown_Timer_Help, it says it cannot find the file.
No you didn't get it, that file will only be present on your dev machine. After you deploy your program, the file will be embedded in your program and cannot be printed. You'll have to write the code that saves the file from the resource to disk, then prints it. For example:
Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
Dim path As String = Application.UserAppDataPath
path = System.IO.Path.Combine(path, "Help.rtf")
System.IO.File.WriteAllText(path, My.Resources.Countdown_Timer_Help)
Dim printProcess As New Process
printProcess.StartInfo.CreateNoWindow = True
printProcess.StartInfo.FileName = path
printProcess.StartInfo.Verb = "Print"
printProcess.Start()
End Sub
Given that you have to save the resource to a file, it probably makes more sense to simply deploy the file with your app instead of embedding it as a resource and writing it to disk over and over again. Use Application.ExecutablePath to locate the file. To make that work at debug time you have to copy the file to bin\Debug. Do so by adding the file to your project with Project + Add Existing Item and setting the Copy to Output Directory property to Copy if Newer.
OK, I got it.
System.IO.Path.GetFullPath(Application.StartupPath & "\..\..\Resources\") & "Countdown_Timer_Help.rtf"