startup folder path for Current user and local machine - vb.net

How do i get the startup folder path for "Current user" and "All user" in VB.net?

Try
Environment.GetEnvironmentVariable("ALLUSERSPROFILE") 'All Users Directory'
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)) 'Current User Directory'
With the Environment.SpecialFolder enumeration you also have available a Startup and a CommonStartup enumeration. They map to the current user and the all users startup directory.

Im unclear about exatly what location you want ill give you a wey to get Environment Variables.
Private Function GetEnvironmentVariable(ByVal var As String) As String
var = Environment.GetEnvironmentVariable(var)
Return var
End Function
Then pass it the name of the Environment Variable you want.
If you are going to add more to the paths like in Rudu's post, you should keep in mind that paths are different of different operating systems.

Related

OpenFileDialog.InitialDirectory returns empty string instead of the path that opens in testing

I would like to point new users to the proper directory to where the file type may be found. However, I don't want to hamper the efficiency of experienced users, as there are more specific sub folders that they may wish to remain in throughout multiple file openings.
I found some context for openfileDialog for c++ here: Initial directory is not working for CFileDialog
However I am interested in a VB solution. Here is Microsoft's documentation:
https://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.initialdirectory(v=vs.110).aspx
in which they state
The InitialDirectory property is typically set using one of the following sources:
A path that was previously used in the program, perhaps retained from the last directory or file operation.
Here is my code:
If Not ImportDialog.InitialDirectory.Contains("Direct Access\Shell\Customer Invoices") Then
ImportDialog.InitialDirectory = "....\Direct Access\Shell\Customer Invoices\"
End If
How can I determine if a user would automatically be sent to this directory or a subdirectory in the tree if getting InitialDirectory is unreliable?
I saved the most recently opened folder and redirected the file path depending on if the user preferred a different path:
If _lastOpenFolder = "" Then
ImportDialog.InitialDirectory = "Direct Access\Shell\Customer Invoices\"
Else
ImportDialog.InitialDirectory = _lastOpenFolder
End If
If ImportDialog.ShowDialog = Windows.Forms.DialogResult.OK Then
_lastOpenFolder = ImportDialog.FileName.Substring(0, ImportDialog.FileName.LastIndexOf("\"))
_lastOpenFolder = _lastOpenFolder.Substring(0, _lastOpenFolder.LastIndexOf("\"))
End If

creating a folder and verifying that the path is ok

I want to create a folder in my VB .NET app but I can't get to verify that the path is correct. For example, if I enter
My.Computer.FileSystem.CreateDirectory("lol it will work")
It works... While it doesn't look like a folder path at all... How can I verify that the path entered is correct ? And since it doesn't throw any exception, the folder must be created somewhere, but where ? I can't find it...
Thank you
Your Directory name "lol it will work" is a valid name.
When you don't provide an explicit path, My.Computer.FileSystem.CreateDirectory() (as well as some other methods/functions) will assume the string you provided is the path to a directory which relative path is your Application's current directory.
So it doesn't matter whether you're passing a complete path (that looks like a valid folder path) or a partial path/folder name that will be associated with the application's Directory as long as :
the resolved Path is a valid path (that doesn't contains invalid chars or missing folder name separator)
you (your application) have access to that path
the resulting path doesn't exceed the max allowed number of characters.
you don't encounter some specific Exceptions...
So, how do you know your application current working path ?
Since you used My.Application.FileSystem :
My.Computer.FileSystem.CurrentDirectory ' Read/Write Property As String
You can use System.IO :
System.IO.Directory.GetCurrentDirectory() ' Get a String
System.IO.Directory.SetCurrentDirectory(NewPath) ' Set
You can also use System.Environment.Directory
Environment.CurrentDirectory ' Read/Write Property As String
Both three (My.Computer.FileSystem, System.IO.Directory and Environment) are writable, and returns the current directory to be resolved in case you're providing relative paths in your application.
So, to answer your question : "How can I verify that the path entered is correct ?"
If you just created the Directory and you get no exception, then the name of your (relative) directory is valid, and the directory has been created :
My.Computer.FileSystem.CreateDirectory("lol it will work")
' Verification :
If System.IO.Directory.Exists("lol it will work") Then
MessageBox.Show("The Directory has been created !")
Else
MessageBox.Show("The Directory has'n been created !")
End If
' Shows "The Directory has been created !"
So you know that even other Functions/Methods can resolve relative path (not all though) by fallbacking to the defined Relative Working Path of your Application.
The test above is the same as :
System.IO.Directory.Exists( _
Path.Combine(Environment.CurrentDirectory, "lol it will work"))
CAUTION :
Due to the writable nature of those objects, your application
may change the Current Directory any time.
Consider :
the use of alternative objects/variables to get your working directory or similar
working with only explicit paths
using a global/static variable that stores the CurrentDirectory upon startup (can fail very easily)
restoring the CurrentDirectory whenever you're changing it (though you will use at a time or another an object that changes the CurrentDirectory without warning - read the documentation of that object whenever it involves a directory manipulation; OpenFileDialog for example which has different behaviours on XP and Win7/8) - This move is the least recommended.
Alternates :
AppDomain.CurrentDomain
AppDomain.CurrentDomain.BaseDirectory
This is a ReadOnly Property. It returns the path to the directory your assembly (application) were loaded from. Caution ! This path has a trailing "\" like :
G:\Tools\...\Sources\bin\Debug\ ' <- !!!
Assembly.GetExecutingAssembly().Location
System.IO.Directory.GetParent(Assembly.GetExecutingAssembly().Location)
This will also return the path to the directory the assembly were loaded from, but without the trailing "\" due to the use of GetParent()
Using Assembly to retrieve a path is useful when you're dealing with dependencies where not all Assemblies are loaded from the same directory. Codes that uses relative paths should use this approach instead of the classic ones.
I assume the same applies for Thread Domain if you want to get deep in multithreads (while I'm not really sure of the relevant aspect of this assumption - Never used this one !) :
Thread.GetDomain().BaseDirectory ' ReadOnly
And the good old Application.StartupPath
Application.StartupPath ' ReadOnly
...which also has a trailing "\". You can't access StartupPath until the application has actually started ! However, I've never checked whether it's working well when you start another process from your application and using that through the other process... (if it's possible... just imagining though)

How can I change my connectionString in app.config file at runtime?

I created my vb.net project to .exe file.
During installation on another machine, one can change the location of installing package to any drive.
In my project, I have set my app.config to point the Database that is available in c:\project.
If I suppose, while installation, when I change the location of installation to **d:** or anywhere, I get invalid access db.
What I want is:
I want to reconfigure my app.config file automatically, by detecting its current db location.
Imports System.Configuration
Imports System.Configuration.ConfigurationManager
Dim config As System.Configuration.Configuration = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
config.ConnectionStrings.ConnectionStrings("MyProject.Properties.Settings.MyProjectConString").ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;DataSource=|DataDirectory|\SampleDB;Persist Security Info=True;"
config.Save(ConfigurationSaveMode.Modified)
Where MyProject.Properties.Settings.MyProjectConString is the name of your project and connection string.
Although this is too late to answer as the question is very old but I think this might help someone else in the future.
So, there is a way to change the Connection String value in the runtime. Since connection string is a read-only item like all other items that are on Application Scope under My.Settings so we can't change it using My.Setting.ConnectionString = "Something". But here is the code by which you can solve the issue and change any My.Settings item that is on Application Scope in the runtime.
So the code is,
My.Settings.Item("ConnectionString") = "Something"
simple...
MsgBox(My.Settings.Item("remoteAddress").ToString)
My.Settings.Item("remoteAddress") = "abcserver.servebbs.net"
My.Settings.Save()
MsgBox(My.Settings.Item("remoteAddress").ToString)
You have three options:
1.) Create and use a folder in C:\Databse and set your connection string at design time.
2.)Add the database to the project's data source at design time, then use '|Data Directory|\mydb.mdb' as your connection string.
3.) And if you use sqlserver, you don't need to worry about the location of the database once you have attached the database to sqlserver. You only need to use the proper connection string eg 'Data Source=.; Database = mydb; Integrated Security = False; Username=myusername; Password = mypassword; User Instance = false'.
The above is an example of a sql server with SQL Authentication mode as login, if you use Windows Authentication, set Integrated Security = True and remove both username and password.

How do i download a file with CA-VO

I'd like to download a file using HTTP. How do I do it?
I have investigated this further and have re-ordered my suggestions from last week as a result:
The class 'CHttp' in VO's 'Internet' library has a method GetFile (the VO 2.5 "what's new" has a brief description on page 10). I've not tried it, though. You'll probably want something like this:
local oSession as CHttp
local lSuccess as logic
oSession := CHttp{}
oSession:ConnectRemote("foo.example.com") // Server domain name
lSuccess := oSession:GetFile("bar/baz.pdf",; // Remote filename
"c:\temp\baz.pdf",; // Local filename
lFailIfAlreadyExists)
oSession:CloseRemote()
// If lSuccess, the file should be downloaded to cLocalFileName.
// I don't know whether the filename arguments should use / or \ for directory separators.
I think another way is to use the Windows ShellExecute function to invoke an external program which downloads the file. I found an example of ShellExecute here. I haven't tried this as I don't have a VO compiler (or help file!) available to me at the moment. I'm not sure whether this is a good way or not, and I don't know whether it's safe from people trying to run a malicious command by supplying a sneaky filename. But I think the following might work. It assumes you have the program curl.exe (see: curl) on your path, which is used for downloading the file. You may need the fully path of curl.exe instead. I'm not sure where the file will be saved by default (I think you can specify a working directory in the parameter labelled lpDirectory)
local cParameters as string
local cURL:="http://www.example.com/interesting.htm" as string
local cLocalFile:="savefile.html" as string
cParameters := "-o "+cLocalFile+" "+cURL
ShellExecute(NULL /*Window handle*/,;
String2PSZ("open"),;
String2PSZ("curl.exe"),;
String2PSZ(cParameters),;
NULL_PTR /* lpDirectory */,;
SW_SHOWNORMAL)
See also the MSDN page for ShellExecute.
There appears to be a method App:Run(cCommand) which can be used to start external applications

"The directory name is invalid" error on Process.Start?

I am writing a launcher program, and when I go to start the process I get the "The directory name is invalid" error. Here is the code that is launching the process:
Const DEBUG_ROOT = _
"Z:\Kiosk_JC\KioskSignIn.root\KioskSignIn\KioskSignIn\KioskSignIn\bin\Debug"
Dim oKiosk As New System.Diagnostics.Process
oKiosk.StartInfo.UserName = oEnc.Decrypt(Username)
oKiosk.StartInfo.Password = oEnc.DecryptSecure(Password)
oKiosk.StartInfo.Domain = oEnc.Decrypt(Domain)
''// The AddBS function appends a '\' to the passed string if it is not present
oKiosk.StartInfo.WorkingDirectory = AddBS(DEBUG_ROOT)
oKiosk.StartInfo.FileName = "KioskSignIn.exe"
oKiosk.StartInfo.UseShellExecute = False
Dim proc As Process = Nothing
proc = System.Diagnostics.Process.Start(oKiosk.StartInfo)
I saw on another question here that I needed to set the WorkingDirectory (before I started searching I was getting the error). Even though I have this property set, I am still getting the error. Any thoughts?
More info
I should also note that my Z:\ is a on my network. I have a function that resolves a path to UNC. When I ran this function on DEBUG_ROOT, I get the same error.
I tried moving the application to c:\kiosk. Same result. I am logged in as the user I am impersonating, so I have access to all shares and files.
Here is the link, for some reason the URL formating wants to consume all the text after the link is designated:
Referred Post
Mapped drives are per-user. You are likely starting the process with a different user.
Sounds like the process can't see the Z: drive or doesn't have security access. What user context does the app run under? Perhaps the Z: drive is not available in that context.
I got the same error as you do. most likely the user you use to run the process does not have access to specified resource (exe file)
try to move your exe to some other location and/or give your user access rights to the file.