How to write a text file to a desktop sub-folder in vb.net - 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.

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 register an icon to a file association?

There are two file extentions called .luo and .luda.
When the program loads the .luo and .luda are assigned.
The variables path and path2 contains the location to the icons.
Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim path, path2 As String
path = Application.StartupPath & "ludafile.ico"
path2 = Application.StartupPath & "luofile.ico"
My.Computer.Registry.ClassesRoot.CreateSubKey(".luda").SetValue("", "Luda Solution (.luda)", Microsoft.Win32.RegistryValueKind.String)
My.Computer.Registry.ClassesRoot.CreateSubKey(".luo").SetValue("", "Luda Page File (.luo)", Microsoft.Win32.RegistryValueKind.String)
My.Computer.Registry.ClassesRoot.CreateSubKey("LudaCreate\shell\open\command").SetValue("", Application.ExecutablePath & " ""%l"" ", Microsoft.Win32.RegistryValueKind.String)
End Sub
The code above succesfully works but I want to register an icon to these files.
One icon for .luda and another for .luo.

File Association for my own Visual Basic application

I made my application that can read some specific extension on load in Visual Basic 2017.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
If Environment.GetCommandLineArgs(1).ToString = My.Application.Info.DirectoryPath.ToString + "\" + My.Application.Info.AssemblyName + ".exe" Then
Else
If System.IO.Path.GetExtension(Environment.GetCommandLineArgs(1)) = ".myOwnExt" Then
Dim fileReader As String
fileReader = My.Computer.FileSystem.ReadAllText(Environment.GetCommandLineArgs(1).ToString)
MsgBox(fileReader)
End If
End If
End Sub
But I want to make my program default for that extension and I want to set my icon for those files. Is it possible to make it happen with Visual Basic?
Your code would look something like this...
My.Computer.Registry.ClassesRoot.CreateSubKey(".myOwnExt").SetValue("", _
"myOwnExt", Microsoft.Win32.RegistryValueKind.String)
My.Computer.Registry.ClassesRoot.CreateSubKey("MyProgramName\shell\open\command").SetValue("", _
Application.ExecutablePath & " ""%l"" ", Microsoft.Win32.RegistryValueKind.String)
Here is a full example on how to do this in VB .NET. Like mentioned above you need to change some registry settings.
https://www.codeproject.com/Articles/18594/File-Association-in-VB-NET
On a quick glance at your code GetCommandLineArgs(1) needs to be changed to GetCommandLineArgs(0) to get this working.

import image to picture box from desktop user

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 +

Gaining authorize Startup shortcut for All User

When my program wanted to add a startup shortcut for All User in Win 7 (or Vista), it got an "Unauthorized Access Exception", even i login as admin.
How do get authorize access for All User in my program?
Here is the code:
Imports IWshRuntimeLibrary
Public Class Form1
Dim AppName As String = "StartUp ShortCut"
Dim startUpFolderPathALLUSERfWin7 As String = Environment.GetEnvironmentVariable(("ALLUSERSPROFILE") & "\Microsoft\Windows\Start Menu\Programs\Startup")
Private Sub Create_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim lnkPathAllUserWin7 As String = startUpFolderPathALLUSERfWin7 & "\" & AppName & ".lnk" 'need permission
Dim appPath As String = My.Computer.FileSystem.CurrentDirectory & "\" & AppName & ".exe"
Try
Dim wshs As IWshShell_Class = New IWshShell_Class
Dim shortcut As IWshShortcut_Class = TryCast(wshs.CreateShortcut(lnkPathAllUserWin7), IWshShortcut_Class)
shortcut.Description = "This is a shortcut to " & AppName
shortcut.TargetPath = appPath
shortcut.IconLocation = appPath + ",0"
shortcut.Save()
MsgBox("ShortCut File Created")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
End Class
You need to change
Dim startUpFolderPathALLUSERfWin7 As String = Environment.GetEnvironmentVariable(("ALLUSERSPROFILE") & "\Microsoft\Windows\Start Menu\Programs\Startup")
To
Dim startUpFolderPathALLUSERfWin7 As String = Environment.GetEnvironmentVariable("ALLUSERSPROFILE") & "\Microsoft\Windows\Start Menu\Programs\Startup"
Note the difference you have the string "\Microsoft\Windows\Start Menu\Programs\Startup" added as part of the environment variable you are trying to find and was coming back as nothing, not added to the found variable. After making the change your program will write to the startup directory.
i try the above and it create a folder in my D:\, don't know why?
Anyway i found out it is the UAC that my program need to deal with (some adjustment on Application Manifest File are needed).
thanks for your help Mark.