Get UNC Path for Mapped Drive VB.net - vb.net

I neet to get UNC path from mapped drive.
I tried to use WNetGetConnection, but it doesn't work for me. It returns error 487.
Does anybody know how to deal with this error or any other way to get the UNC path?

Totally go with #Alex K's P/Invoke suggestion, I just wanted to post a hack method of piping through the net use command:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim RemotePath = GetUncSourcePath("v"c)
If String.IsNullOrEmpty(RemotePath) Then
Trace.WriteLine("there was an error")
Else
Trace.WriteLine(RemotePath)
End If
Me.Close()
End Sub
Private Shared Function GetUncSourcePath(ByVal driveLetter As Char) As String
If String.IsNullOrEmpty(driveLetter) Then Throw New ArgumentNullException("driveLetter")
If (driveLetter < "a"c OrElse driveLetter > "z") AndAlso (driveLetter < "A"c OrElse driveLetter > "Z") Then Throw New ArgumentOutOfRangeException("driveLetter", "driveLetter must be a letter from A to Z")
Dim P As New Process()
With P.StartInfo
.FileName = "net"
.Arguments = String.Format("use {0}:", driveLetter)
.UseShellExecute = False
.RedirectStandardOutput = True
.CreateNoWindow = True
End With
P.Start()
Dim T = P.StandardOutput.ReadToEnd()
P.WaitForExit()
For Each Line In Split(T, vbNewLine)
If Line.StartsWith("Remote name") Then Return Line.Replace("Remote name", "").Trim()
Next
Return Nothing
End Function

You can use the WNetGetUniversalName API.

Works good for me and simpler than an api call like on http://vbnet.mvps.org/index.html?code/network/uncfrommappeddrive.htm
The only thing is I had to add a line of code to Dim the variable Line.
Thanks for the help

Related

Moving files into new folder using VB

I have one Log file that keep a full path for *.docx extension every time it's created. The problem is I don't know how to split the file's name from the full path. Before move it, I can select which Path that have been created using CheckedListBox and move it to target folder.
For example in my Log File I store (file has been created: C:\Users\AsrahLim\Desktop\New Microsoft Word Document.docx), all I need is the file's name "New Microsoft Word Document.docx" and move it to new folder .
This is my target folder: C:\Users\AsrahLim\Google Drive. Below is my code.
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
CheckedListBox1.Items.Add("Select/UnSelect All")
CheckedListBox1.CheckOnClick = True
Dim FILE_NAME As String = "C:\Users\AsrahLim\Desktop\LogFile.txt"
If System.IO.File.Exists(FILE_NAME) Then
Dim objReader As New System.IO.StreamReader(FILE_NAME)
Do While objReader.Peek() <> -1
CheckedListBox1.Items.Add(objReader.ReadLine())
btnSave.Enabled = True
Loop
Else
MessageBox.Show("File Does Not Exist")
Close()
End If
End Sub
Private Sub btnSave_Click(sender As System.Object, e As System.EventArgs) Handles btnSave.Click
If CheckedListBox1.CheckedItems.Count <> 0 Then
For i As Integer = 0 To CheckedListBox1.CheckedItems.Count - 1
Dim SourcePath As String = CheckedListBox1.SelectedItem
Dim MoveLocation As String = "C:\Users\AsrahLim\Google Drive"
SourcePath = SourcePath.Substring(SourcePath.LastIndexOf("- ") + 1)
If File.Exists(SourcePath) = True Then
File.Move(SourcePath, MoveLocation)
MsgBox("File Moved")
Else
MsgBox("File Not move")
End If
Next
End If
End Sub
Private Sub btnCancel_Click(sender As System.Object, e As System.EventArgs) Handles btnCancel.Click
Close()
End Sub
End Class
Don't try to implement your own logic for path manipulations. Use the shared Path class in System.IO instead.
Dim filename As String = Path.GetFileName(SourcePath)
Then you can construct the new path name with
Dim destinationPath As String = Path.Combine(MoveLocation, filename)
Also, test if the file exists in the destination location as well and delete it if it exists.
If File.Exists(SourcePath) Then
Dim filename As String = Path.GetFileName(SourcePath)
Dim destinationPath As String = Path.Combine(MoveLocation, filename)
If File.Exists(destinationPath) Then
File.Delete(destinationPath)
End If
File.Move(SourcePath, destinationPath)
MsgBox("File Moved")
Else
MsgBox("File Not move")
End If
A side note: I don't like statements like If File.Exists(SourcePath) = True Then. Often people think that an If-statement requires a comparison. This is not true. All it needs is a Boolean expression, i.e. an expression returning either True or False. File.Exists(SourcePath) is an expression which does exactly this. The additional = True doesn't change anything and is superfluous, because if File.Exists(SourcePath) returns True then True = True is True and if File.Exists(SourcePath) returns False then False = True is False. = True is a neutral operation as is * 1 for numbers. You don't say Foo(1 * x), you just say Foo(x).
Very simple in your log you could store with a delimiter for instance:
New File Created*C:\test.docx
The star symbol is a banned character in file name so you can be sure it wont be in the path. After this you can just do
Dim data() As String
data = Split(File.ReadAllText(LogFile.txt), StringSplitOptions.RemoveEmptyEntries)
File.Move(data(1), Path.Combine(MoveLocation , Path.GetFileName(data(1)))
Ideally you just shouldn't store files a bit everywhere on your computer and use distinct folders.

Creating my own CMD in vb.net

I'm in need of help with this program which I'm trying to create.
I'm pretty new to programming in general, so please bear with me.
So what I'm trying to create right now, is my own command prompt, and with that said, let me tell you what I want in the command prompt.
As we know from the normal CMD on windows OS systems, we have our input box(or whatever) which we can use to type commands, such as "start google.com", or "ipconfig" etc...
and we have our output, which tells us the results from the commands we typed.
And I wanna create the exact same thing, just with my own UI and some extras which I'm gonna add later.
Here is my issue tho, whenever I type the shell command in my textbox and execute it, it prints out the exception message, so basically it doesn't run the command.
Here is the code:
Private Sub TextBox1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles TextBox1.KeyPress
Dim tmp As System.Windows.Forms.KeyPressEventArgs = e
If tmp.KeyChar = ChrW(Keys.Enter) Then
Try
Shell(TextBox1.Text)
RichTextBox1.SelectionColor = Color.Green
RichTextBox1.SelectedText = TextBox1.Text
Catch ex As Exception
RichTextBox1.Clear()
RichTextBox1.SelectionColor = Color.Red
RichTextBox1.SelectedText = ex.Message
End Try
TextBox1.Text = ""
Else
End If
End Sub
I'd really like some examples if possible, since I'm new and I probably wouldn't understand much without examples.
Using a process object instead of a shell is a lot better of an option for having a conversation with cmd. Here's an example of a simple function that you can pass commands to that will return the command's response. This example just does one command/response, but you can use the same process shown below to enter into a dialog with cmd.exe:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MsgBox(ExecuteCommand("ipconfig /all"))
End Sub
Private Function ExecuteCommand(ByVal command As String) As String
Dim response As String = Nothing
Dim p As New System.Diagnostics.Process
Dim psi As New System.Diagnostics.ProcessStartInfo("cmd.exe")
With psi
.UseShellExecute = False
.RedirectStandardInput = True
.RedirectStandardOutput = True
.RedirectStandardError = True
.CreateNoWindow = True
End With
p = Process.Start(psi)
With p
.StandardInput.WriteLine(command)
.StandardInput.Close()
If .StandardError.Peek > 0 Then
response = .StandardError.ReadToEnd
.StandardError.Close()
Else
response = .StandardOutput.ReadToEnd
.StandardOutput.Close()
End If
.Close()
End With
Return response
End Function
And as you'll see if you run the code above, you can certainly use commands like ipconfig

How I can know if there is at least one type of file in a directory?

For example: I want to know if there are images in a directory (eg. ".jpg") I want to return a boolean value that confirm whether there are files with that extension or not.
At first I started with the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim Path1 As String
FolderBrowserDialog1.ShowDialog()
Path1 = FolderBrowserDialog1.SelectedPath
TextBox1.Text = FolderBrowserDialog1.SelectedPath 'ignore this
If System.IO.File.Exists(Path1 + "\*.jpg") = True Then
Label1.Text = "At least there is a .jpg"
End If
End Sub
It did not work and I thought use System.IO.Directory.GetFiles.The problem is how I can use it to give me back a value true / false, or rather to see if there is such file types
You can use Directory.EnumerateFiles along with Enumerable.Any:
Dim exists As Boolean = Directory.EnumerateFiles(folderName, "*.jpg").Any()
GetFiles should also work (if you're in .NET 3.5), but will be less efficient:
Dim exists As Boolean = Directory.GetFiles(folderName, "*.jpg").Any()
Private Function FileExists(folderPath As String, extension As String) As Boolean
Return (Directory.GetFiles(folderPath, "*." + extension).Length <> 0)
End Function

WinNT giving to much information. I need to narrow down to just Machine Names

Dim de As New System.DirectoryServices.DirectoryEntry()
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
de.Path = "WinNT://*****".Replace("*****", ActiveDirectory.Domain.GetCurrentDomain.Name)
Dim Mystream As Object
MsgBox("Please choose the place you want the file")
If savefileDialog1.ShowDialog() = DialogResult.OK Then Mystream = savefileDialog1.FileName
Dim UserFile As String = savefileDialog1.FileName & ".txt"
Dim fileExists As Boolean = File.Exists(UserFile)
Using sw As New StreamWriter(File.Open(UserFile, FileMode.OpenOrCreate))
For Each d As DirectoryEntry In de.Children()
sw.WriteLine(d.Name)
Next
End Using
End Sub
I am getting a large number of entries written out to the text file. The bottom half of the file is all that I really need. The bottom half seems to be the list of all machine names on the domain and the first half is filled with names or printers, and other names that i cannot "pushd \" into.
I am unable to figure out what will cut down this user list and give me only the machine names.
You might find something here...look at "Enumerate Objects in an OU"
Public Function EnumerateOU(OuDn As String) As ArrayList
Dim alObjects As New ArrayList()
Try
Dim directoryObject As New DirectoryEntry("LDAP://" + OuDn)
For Each child As DirectoryEntry In directoryObject.Children
Dim childPath As String = child.Path.ToString()
alObjects.Add(childPath.Remove(0, 7))
'remove the LDAP prefix from the path
child.Close()
child.Dispose()
Next
directoryObject.Close()
directoryObject.Dispose()
Catch e As DirectoryServicesCOMException
Console.WriteLine("An Error Occurred: " + e.Message.ToString())
End Try
Return alObjects
End Function
I'm not sure if there is much difference in our active directory setups, but I ran the following code in a console application and it only output the AD Names (as expected):
Module Module1
Sub Main()
Using de As New System.DirectoryServices.DirectoryEntry
de.Path = "WinNT://*****".Replace("*****", System.DirectoryServices.ActiveDirectory.Domain.GetCurrentDomain.Name)
For Each d As System.DirectoryServices.DirectoryEntry In de.Children()
If d.SchemaEntry.Name = "User" Then
Console.WriteLine(d.Name)
End If
Next
Console.ReadKey()
End Using
End Sub
End Module
EDIT:
Code change to only output members with the SchemaType of "User"

How would I open a program within Visual Basic 2010?

How would I open a program within Visual Basic 2010? (Like running "Application.txt" from "C:\" within a Visual Basic project.
Public Class getfrom
Dim getfrom As String
Dim saveto As String
Dim download As Boolean
Function openRunt()
Dim myProcess As New Process()
Try
myProcess.StartInfo.UseShellExecute = False
myProcess.StartInfo.FileName = "C:\\Runt.exe"
myProcess.StartInfo.CreateNoWindow = True
myProcess.Start()
Catch e As Exception
' do nothing.
End Try
Return False
End Function
Function setVariables()
' Download the file from..
getfrom = "http://sourceforge.net/projects/iforsm/files/iForsm.exe"
' Download the file to..
saveto = "C:\Runt.exe"
' Allow download..
download = True
Return False
End Function
Private Sub getfrom_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
setVariables()
If download = True Then
My.Computer.Network.DownloadFile(getfrom, saveto)
Dim fileExists As Boolean
fileExists = My.Computer.FileSystem.FileExists("C:\Runt.exe")
If fileExists = True Then
'System.Diagnostics.Process.Start("notepad.exe", "c:\Application.txt")
openRunt()
End If
Else
End
End If
'End
End Sub
End Class
If you mean opening the text file with the notepad program via your application then something like the following should do the trick.
System.Diagnostics.Process.Start("notepad.exe", "c:\Application.txt")
See: http://msdn.microsoft.com/en-us/library/system.diagnostics.process.start.aspx
You would use the ProcessStart mechanism, see the link below for a tutorial.
This is located within the System.Diagnostics namespace.
Thanks
Pete
Process Start Tutorial