import image to picture box from desktop user - vb.net

I want to import a picture from folder which created by project when installed on user desktop but each user have different user name , how can i import from picture from dsektop user
Here is My code
Private Sub Button2_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles Button2.Click
PictureBox1.Image = Image.FromFile("(My.Computer.FileSystem.SpecialDirectories.Desktop, "New folder") \" + ID.Text + ".png")
end sub

Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
this will resolve to the desktop folder for the current user. Are you really creating folders on the desktop? Usually data and subfolders are stored in AppData.
EDIT
I SUSPECT you might have need of this folder in other places and even if not it can be saved and 'fixed' before hand. Elsewhere, like when the app starts:
Friend mUserFolder As String
mUserFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
' your code was not adding the required backslash
mUserFolder &= "\Data\" ' append the sub folder name
Now to load the file in button click the code is simpler to read and debug:
PictureBox1.Image = Image.FromFile(muserFolder & ID.Text & ".png")
Also use & for concatenating strings instead of +

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

How to write a text file to a desktop sub-folder in vb.net

Please I want to write a text file to a sub-folder I have created within a folder on the desktop i.e.
Desktop Folder > Sub-folder > Text file
The code I came up with is shown below. I have created the sub-folder within the parent desktop folder, but cannot locate this sub-folder to write and save the text file. Please I would appreciate any suggestions. I am using Visual Basic 2010 Express. Thank you in advance.
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
‘Check if a sub-folder with the title specified in Textbox1 does not exist in desktop folder titled Family
If (Not System.IO.Directory.Exists("C:\Users\" & Environ("username") & "\Desktop\Family\" & TextBox1.Text)) Then
‘Create a sub-folder within desktop folder titled Family with the title specified in Textbox1
System.IO.Directory.CreateDirectory("C:\Users\" & Environ("username") & "\Desktop\Family\" & TextBox1.Text)
End If
Dim fileTXT As New IO.StreamWriter("C:\Users\" & Environ("username") & "\Desktop\Family\" & TextBox1.Text & TextBox1.Text & ".TXT")
fileTXT.Write(TextBox2.Text)
fileTXT.WriteLine("")
Close()
End Sub
I would write your code this way:
Dim di = New DirectoryInfo(Path.Combine( _
Environment.GetFolderPath(Environment.SpecialFolder.Desktop), _
"Family\" & TextBox1.Text))
If Not di.Exists
di.Create()
End If
Dim fn = Path.Combine(di.FullName, TextBox1.Text + ".TXT")
File.WriteAllText(fn, TextBox2.Text + Environment.NewLine)
Try this to get the desktop folder:
Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
You can then use System.IO.Path.Combine to add the Family subfolder. Make sure that subfolder exists before creating any folders underneath it.

Opening an Empty Directory from a Windows Form - VB.net

I'm trying to open a directory via my Windows Form created in VB.Net but every solution I've found doesn't seem to work.
Currently I'm using-
Dim path As String = Directory.GetCurrentDirectory()
Private Sub logDirBTN_Click(sender As Object, e As EventArgs) Handles logDirBTN.Click
Process.Start(path + "\Resources\Logs")
End Sub
Which returns "The system cannot find the file specified" exception. That's interesting because I know the folder is there. Furthermore this button's functionality works without any issue and from what I can tell the only difference is I'm opening a text file rather than an empty directory-
Private Sub stationListBTN_Click(sender As Object, e As EventArgs) Handles stationListBTN.Click
Process.Start("notepad.exe", path + "\Resources\StationList\StationList.txt")
End Sub
Here are all the other things I've tried-
Private Sub logDirBTN_Click(sender As Object, e As EventArgs) Handles logDirBTN.Click
'Process.Start("explorer.exe", path + "\Resources\Logs")
'Shell("explorer.exe", path + "\Resources\Logs", vbNormalFocus)
'Application.StartupPath & path + "\Resources\Logs"
'Shell(path + "\Resources\Logs", vbNormalFocus)
End Sub
Any help is greatly appreciated.
Dim MyProcess As New Process()
MyProcess.StartInfo.FileName = "explorer.exe"
MyProcess.StartInfo.Arguments = "C:\Blah"
MyProcess.Start()
MyProcess.WaitForExit()
MyProcess.Close()
MyProcess.Dispose()
Or just...
Process.Start("explorer.exe", "C:\FTP\")
Application.StartupPath is going to get you to your bin\Debug or bin\Release folder by the way, whatever folder the *.exe is in.
I'm guessing this is what you're looking for:
Process.Start("explorer.exe", Application.StartupPath & "\Resources\Logs")
Also, don't use + for joining strings. Use &
I assume you are trying to invoke Windows Explorer.
Add a trailing \ in the call to .Start
IO.Directory.CreateDirectory("C:\temp\temp")
Process.Start("c:\temp\temp\")
In the OP first example you were trying to open a file 'Logs'

How do I discover the user's Desktop folder?

I'm making a little application in visual studio which loads a ROM in an emulator.
I have two emulators and 20 ROMs.
I made a form and added a few buttons. When you click the Button it opens a new form and closes the old one. Then on the new form I have four buttons: each one loads a different ROM in an emulator. So when you press Button1 this code is triggered:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles yellow.Click
Shell("C:\Users\shifty\Desktop\pokemon games\Emulator\VBA\VisualBoyAdvance.exe ""C:\Users\shifty\Desktop\pokemon games\Roms\Yellow\Pokemon Yellow.gb""", vbNormalFocus)
End Sub
It works fine - I click it and it loads the game in the emulator. The bit im having trouble with is the file paths. If I send this application to a friend, it would still look for "C:\Users\shifty\Desktop\" - but that's on my computer, not his.
Is there a way to make the application look for the file on his computer (without changing the file path to (C:\Users\""his user name""\Desktop))
Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
This will resolve to be the desktop folder for the current user.
It will even work between XP, vista and Windows 7 properly.
Old post but I have to side with Mc Shifty. You can't assume that everyone is a coding expert. If they were then they wouldn't be here asking questions like that.
None of the answers given above were complete
Environment.GetFolderPath(Environment.SpecialFolder.Desktop)) <<< includes and extra )
Environment.GetFolderPath(Environment.SpecialFolder.Desktop)); <<< extra ) and the ; is C or java not VB which he is obviously using by his example code.
Both of those only give you half of the required code to generate something usable.
Dim s As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
The above code will give you the result needed, c:\users\shifty\desktop
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles yellow.Click
Dim s As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Shell(s & "\Desktop\pokemon games\Emulator\VBA\VisualBoyAdvance.exe " & s & "\pokemon games\Roms\Yellow\Pokemon Yellow.gb""", vbNormalFocus)
End Sub
There's a mechanism to get the current user's Desktop directory, using Environment.SpecialFolder.
Usage:
Environment.GetFolderPath(Environment.SpecialFolder.Desktop));
I had problems using the Environment.GetFolderPath method from previous answers.
The following works in VB 2012, My.Computer.FileSystem.SpecialDirectories.Desktop
So, if you have a file on a users desktop named "contacts.txt", the following will display the full path,
' Desktop path
Dim desktopPath = My.Computer.FileSystem.SpecialDirectories.Desktop
' Concatenate desktop path and file name
filePath = desktopPath & "/contacts.txt"
MsgBox(filePath)
Documentation
Really old post at this point, but hey, found what I was looking for.
MC SH1FTY, I assume you have figured this out already, but to do what you are trying to do:
1) Call in that code that Spence wrote as a variable (I'd declare it Globally, but that's my preference. To do that:
Public userDesktopLoc As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
2) Either use this DIRECTLY in your code, or make another string to concatenate a directory:
Option A)
Public emulatorPath As String = userDesktopLoc & "pokemon games\Emulator\VBA\VisualBoyAdvance.exe "
Public romPath As String = userDesktopLoc & "pokemon games\Roms\Yellow\Pokemon Yellow.gb"
Then, within your Subroutine, replace your current Shell statement with:
Shell(emulatorPath & romPath, vbNormalFocus)
Or, Option B, which is thedsz's answer:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles yellow.Click
Dim s As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Shell(s & "\Desktop\pokemon games\Emulator\VBA\VisualBoyAdvance.exe " & s & "\pokemon games\Roms\Yellow\Pokemon Yellow.gb""", vbNormalFocus)
End Sub
By using that you guarantee that the emulator is on the users desktop. This is not always the case. I know I move things around that I download or a friend sends to me. It's better to use App.Path and make sure your emulator.exe is in the directory with your little front end program (usually the case).
the answer is simple.
put this at the top of the form
"Public thepath As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)"
that ensures that the file is on their desktop!
then" click on your button or whatever you used to open the emu and type
"Process.Start(thepath + "the emulator.exe "+ "the rom you want")
You need to use a file open dialog to choose your path for the two files. Here is an example.
You then use the two paths in your code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles yellow.Click
Shell(emulatorPath + "\"" + romPath + "\"", vbNormalFocus)
End Sub

Can't get VBA to write "http://"as text?

I wrote the code bellow and need the asociated .PGP file to have the text http:// included. the PGP file is namely read by Autocad which requers the "http://" in its text to be able to launch the desierd webpage. problem is , is that VBA is Auto formating the http:// as a code entatie and not writting it to the text based PGP file.
Can any one tell me how to achive what im after?
Private Sub Button6_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button6.Click
Dim FILE_NAME As String = "C:\test.pgp"
If System.IO.File.Exists(FILE_NAME) = True Then
Dim objWriter As New System.IO.StreamWriter(FILE_NAME, True)
objWriter.WriteLine((TextBox5.Text) + "," + " " + "START http://" + (TextBox6.Text) + ", 1,,")
objWriter.Close()
MsgBox("The acad.pgp file was successfully appended…")
Else
MsgBox("File missing reinstall or contact vendor…")
End If
End Sub
Hm, I'tried your code above in VisualStudio 2010. An empty file named C:\test.pgp was appended with the following text:
textbox5, START http://textbox6, 1,,
The text http... is right there. Sometimes, when I open the file in a viewer, this viewer automatically detects the http string and marks it as a hyperlink. But only in this viewer!
So the error seems to be somewhere else, not in the code?