I am trying to get my vb program to read from a file - vb.net

I am trying to get my program to read from a file on visual basic but it keeps saying the file does not exist, I have tried different file paths and other things but i cant seem to get it working.
my code is :
Option Strict On
Imports System.IO
Public Class MOTform
Dim custfile As StreamReader
Dim strCustArray() As String
Dim strCustDetails As String
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
radMOTYes.Checked = True
If File.Exists("cust_db.txt") Then
' Open the file.
custfile = File.OpenText("cust_db.txt")
Else
MessageBox.Show("cust_db.txt" & " does not exist.")
End If
strCustDetails = custfile.ReadLine()
strCustArray = Split(strCustDetails, ",")
Me.Text = strCustDetails
custfile.Close()
End Sub

go to the file you want to read from, right click on it, click Properties, copy the path from Location and insert it to the code

Your code expects the file in the same folder where your program runs because you don't have any kind of path. This is fine when you deploy your final executable because there is no BIN\DEBUG there.
In debug inside VS instead you need to have that file in that folder for the same reason. Your debugged exe runs in that folder. You can add the txt file to your project and change the property Copy to Output Directory to Copy Always.
However, keeping a data file in the same folder where your program runs is not a good practice, in particular if the file is not read only.
The operating system can prevent your application to change that file if you deploy your application in some kind of reserved folder (like C:\program files).
I suggest to use the config file adding an AppSettings key to specify the folder where you keep the file and then reading that key at runtime to build your path
For example
<appSettings>
<add key="DataFolder" value="C:\programdata\myappdatafolder"/>
</appSettings>
and then
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
radMOTYes.Checked = True
Dim fullFileName = Path.Combine(ConfigurationManager.AppSettings("DataFolder"), "cust_db.txt")
If File.Exists(fullFileName) Then
' Open the file.
custfile = File.OpenText(fullFileName)
Else
MessageBox.Show(fullFileName & " does not exist.")
End If
In this way you can change the configuration file to have your file where is most convenient for your scenario

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 can I move a certain file extension into one folder with VB

I am new to VB and would like to create a software that moves a certain file extension into a single folder. I have already built the code that creates a folder on the desktop when clicking the button although after that runs I need to compile a certain file such as (.png) into the folder in created.
This code creates two buttons that when pressed creates a folder called "Pictures" and "Shortcuts".
How would I go about moving all .png files from the desktop into the pictures folder?
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
My.Computer.FileSystem.CreateDirectory(
"C:\Users\bj\Desktop\Pictures")
MessageBox.Show("Pictures Compiled And Cleaned")
End Sub
Private Sub Button1_Click_1(sender As Object, e As EventArgs) Handles Button1.Click
My.Computer.FileSystem.CreateDirectory(
"C:\Users\bj\Desktop\Shortcuts")
MessageBox.Show("Shortcuts Compiled And Cleaned")
End Sub
End Class
We'll start simple. This command will generate an array of all the PNG files' paths on the desktop
Dim filePaths = Io.Directory.GetFiles("C:\Users\bj\Desktop\", "*.png")
We can loop through this array and act on each filepath:
For Each filePath in filePaths
Dim filename = Io.Path.GetFilename(filepath)
Dim newPath = IO.Path.Combine("C:\Users\bj\Desktop\Pictures", filename)
IO.File.Move(filePath, newPath)
Next filePath
We have to pull the filename off the path and put it into a new path, then move from old to new. This I also how you rename files; have a new name in the same folder and use Move. Always use the Path class to cut and combine file paths

How to get a file from Pastebin.com and saving the file on computer in VB.NET

How to get a file from the Pastebin.com and the save the file to the system. In the interface there is a textbox, where a user can paste a link to a pastebin file https://pastebin.com/raw/*a-random-code*, there will be a button to start fetching the file, once the program fetches the file, the file is saved on to the computer as a downloadedtext.txt file.
I found an alternate method very easy.
Private Sub frm1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim filename As String
filename = "C:\Users\sample.txt"
My.Computer.Network.DownloadFile("https://pastebin.com/raw/*enter code*", filename)
End Sub

VB.NET Saving file without save dialog prompt

I need to know how I can save a file, without using save file dialog prompt.
Currently my code is:
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
ProgressBar1.Value = 0
Using sfd As New SaveFileDialog
With sfd
If .ShowDialog = Windows.Forms.DialogResult.OK Then
.DefaultExt = "exe"
.Filter = "Saved.exe (*.exe)|*.exe"
'---Save File---
'---Code to pack the result with UPX packer---
ProgressBar1.Value = 100
MsgBox("Success.", MsgBoxStyle.Information)
End Sub
And I would like to know, how I can save the file with the name "Saved.exe" to the same folder where my application is, without the save file dialog's prompt.
The file needs to be saved on the same folder where the program is, with preconfigured name so the UPX packer knows what to pack.
Hopefully somebody can help me out.
There is a lot of different ways to get the directory:
My.Application.Info.DirectoryPath
Application.Current.BaseDirectory
IO.Path.GetDirectoryName(Application.ExecutablePath)
Windows.Forms.Application.StartupPath
IO.Path.GetDirectoryName(Reflection.Assembly.GetExecutingAssembly().CodeBase)
Once you have the application folder, simply add the name for the filename you want to get a full filename path.
The save file dialog just allows the user to specify where they want to save the file.
If you want to save a file without this dialog you will have to specify the filename yourself.
You can use one of the following code snippets to save the file:
For a Text File:
My.Computer.FileSystem.WriteAllText("C:\SomeDir\YourFile.txt", "Text", True)
For a Binary file:
Dim fileContents() As Byte = {244, 123, 56, 34}
My.Computer.FileSystem.WriteAllBytes("C:\SomeDir\YourFile.bin", fileContents, True)
Note: These are straight from the standard snippets in Visual Studio. Press Ctrl+K, Ctrl+X then navigate to Fundamentals > FileSystem

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.