Accessing file on remote computer - vb.net

I am trying to open a file on a remote computer. The computer I am trying to access has a Domain/Username/Password that are required. I am unable to find out how to use the credentials to access the file.
I don't have much, but I have this so far.
Dim username = "domain\username"
Dim Pass = "password "
Dim path As String = "\\" & FIP & "\C$\Test.log "
Process.Start(path)
I cannot figure out how to incorporate the username/pass into the path to run it.

You need to initialize ProcessStartInfo object and pass that as parameter to Process.start.
Dim path As String = "\\" & FIP & "\C$\Test.log "
Dim RemoteMachine As New ProcessStartInfo(path)
RemoteMachine.UserName = "domain\username"
RemoteMachine.Password = "password"
Process.Start(RemoteMachine)

Related

How can I send a command to a running cmd application started from my application?

My application starts openvpn from the command line like this:
Dim cmdInfo As New ProcessStartInfo("cmd", "/K openvpn.exe " & Chr(34) & ovpnPath & Chr(34))
cmdInfo.WindowStyle = ProcessWindowStyle.Hidden
Process.Start(cmdInfo)
This works great but I have no way of closing openvpn gracefully. I could kill the process but then it doesn't remove the routes etc.
Now I'm looking for a way to send Ctrl+C or F4 to my hidden cmd window to make OpenVPN exit.
Dim opwnfilepath As String = "Opvn file path"
Dim Params As String = " --config """ & opwnfilepath & """
Dim p As New ProcessStartInfo
p.FileName = "C:\Program Files\OpenVPN\bin\openvpn.exe" ' add here openvpn.exe path
p.Arguments = Params
p.WindowStyle = ProcessWindowStyle.Hidden
Process.Start(p)
I use this code work good. if need show what happend in cmd change ProcessWindowStyle.Hidden to ProcessWindowStyle.Normal
Sorry I understand wrong :D
if you close openvpn in task manager , network gone back to your own
try this code
Dim arrProcessx() As Process = System.Diagnostics.Process.GetProcessesByName("openvpn")
For Each psx As Process In arrProcessx
psx.Kill()
Next
tested work for me.

Check for file/subdirectory existence with VB.NET using FtpWebRequest

I have a problem with my FTP upload and I hope you can help me. I'm trying create folders and then upload files to them. What my program should do is checking if a folder already exists, and if not, create a new one with the name checked before. The program runs fine, except for the error described below.
My Problem:
I want to upload a folder called ghandle -> works as intended.
After that, I want to upload a folder called handle -> doesn't work, because the .Contains method that checks the folders on the FTP server, finds ghandle and stops, because ghandle contains handle.
Are there other options like .Contains which will just check for whole words or exact matches?
Here is my source code:
Dim dirname = Path.GetFileNameWithoutExtension(openFileDialogHtml.FileName) & "_files"
Dim ftp = "ftp://" & ftp_address.Text & "/"
Dim user = ftp_user.Text
Dim pass = ftp_password.Text
Dim request As Net.FtpWebRequest = Net.FtpWebRequest.Create(ftp)
Dim creds As Net.NetworkCredential = New Net.NetworkCredential(user, pass)
request.Credentials = creds
Dim resp As Net.FtpWebResponse = Nothing
request.Method = Net.WebRequestMethods.Ftp.ListDirectoryDetails
request.KeepAlive = True
Using resp
resp = request.GetResponse()
Dim sr As StreamReader = New StreamReader(resp.GetResponseStream(), System.Text.Encoding.ASCII)
Dim s As String = sr.ReadToEnd()
If Not s.Contains(dirname) Then
request = Net.FtpWebRequest.Create(ftp & dirname)
request.Credentials = creds
request.Method = Net.WebRequestMethods.Ftp.MakeDirectory
resp = request.GetResponse()
MsgBox("Created folder " & dirname)
Else
MsgBox("Folder " & dirname & " already exists!")
End If
End Using
Thanks in advance
First, use ListDirectory, not ListDirectoryDetails. The ListDirectory returns plain names only, what is enough for your purpose and easy to parse.
Then just split the output to an array of individual file names, using the String.Split method:
Dim names As String() =
sr.ReadToEnd().Split(
New Char() {vbCr, vbLf}, StringSplitOptions.RemoveEmptyEntries)
And use the IEnumerable.Contains extension method to check for given file name:
If Not names.Contains(dirname) Then

VB.NET not copying a folder to new destination

So I want to copy the folder at the end, But, for some reason, it doesn't copy it. I do not get an error message, so the code doesn't have errors, it's just incorrect.
Dim Log As String = System.IO.Path.Combine(DateTime.Now.ToString("yyyy_MM_dd_HHmmss"))
Process.Start("CMD", "/c robocopy.exe " & Source & " " & Destination & " /log:C:\Backup\log_" & Log & ".txt ")
Dim Copy2 As String = ("Backup_" & DateTime.Now.ToString("yyyy_MM_dd_HHmmss"))
Dim Destination2 As String
Destination2 = Destination
Dim copy4 As String = Destination2.Substring(0, Destination2.LastIndexOf("\"))
Dim Copy3 As String = System.IO.Path.Combine(copy4, Copy2)
FileIO.FileSystem.CreateDirectory(Copy3)
My.Computer.FileSystem.MoveDirectory(Destination, Copy3, True)
MsgBox("Backup ist vollendet!")
did you try to end the Process, befor accessing the just copied data ?
Try :
process.kill

& operator string error with string of arguments to processStartInfo

I need to pass a string into the ProcessStartInfo for ffmpeg so that I can call the dim.Argument and have it append the strings and variables from code as I parse through the files.
I have the current filename.mp3 that the code sees in movedFileInfo but it won't allow me to append it to the string using & operators... help?
I know there may be one other way to do this utilizing the ffmpeg command in separate function to simply loop through a directory using "for" but I've not found a successful command for running my ffmpeg.exe nor the ffprompt in windows. I also need to append a carriage return when I write to merge.txt but can't find an example... I'm new to vba.
These commands work but vba is complaining about the & operator in my string with the error The operator '&' is not defined for types 'String' and 'System.IO.FileInfo'.
So what I understand is that the string I'm passing into psi.Arguments doesn't like the fact that I'm sending it a string and a variable appended using the & operator... do I simply use a comma or how do I append the variable movedFileInfo to ffmpeg -i? psi is defined above as ProcessStartInfo... so I'm not sure what types vb recognizes for it... I haven't found info on ProcessStartInfo to kick off my ffmpeg exe.
See code below:
Imports System
Imports System.IO
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
'videos are from SD card always on I:\Private\AVCHD\BDMV\STREAM\
'store files to RAID drives in folders structured as :
' F:\BUILD\FLIGHT#\CAM#\<TAIL_NUMBER>_FLT_<FLT_NUMBER>_UTC_<START_UTC_TIME>_CAM_<CAM_NUMBER>.MTS
'set base dir as directory F:\
Dim dir As String = "C:\"
Dim video_card_dir As String = "C:\1bak\" '"I:\Private\AVCHD\BDMV\STREAM\"
Directory.SetCurrentDirectory(dir)
Dim new_flightnum_directory = dir & Me.BUILD.Text & "\" & FLT.Text & "\"
'establish new video dir> F: \ BUILD \ FLIGHT # \ CAM # \
Dim new_video_directory = dir & Me.BUILD.Text & "\" & FLT.Text & "\" & Me.CAM.Text & "\"
'establish new filename to rename the video file
' TAIL # FLT #
Dim new_filename As String = TAIL.Text & "_" & FLT.Text & "_" & UTC.Text & "_" & CAM.Text
Dim ffmpeg As String = "C:\ffmpeg\bin\ffmpeg.exe"
'****FFMPEG required variables
Dim psi As ProcessStartInfo = New ProcessStartInfo("C:\ffmpeg\bin\ffmpeg.exe")
Dim proc As Process = Process.Start(psi)
psi.UseShellExecute = True
psi.CreateNoWindow = True
'****end FFMPEG required variables
'!!!!!!!!!!!!!!!!!!!!!!!!!!!need to add the processing below to the IF statement aboev so that if the folders exist, the video processing doesn't attempt to run on existing files
' !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~START - MOVE THIS DOWN BELOW CREATION OF FILE STRUCTURE WHEN DOEN DEBUGGING************
'***START MOVING the files from the card to the new directory****
For Each foundFile As String In My.Computer.FileSystem.GetFiles(video_card_dir, Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, "*.MTS")
Dim foundFileInfo As New System.IO.FileInfo(foundFile)
My.Computer.FileSystem.MoveFile(foundFile, new_video_directory & foundFileInfo.Name)
Next
For Each foundFile As String In My.Computer.FileSystem.GetFiles(video_card_dir, Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, "*.MTS")
Dim movedFileInfo As New System.IO.FileInfo(foundFile)
psi.Arguments = "ffmpeg -i " & movedFileInfo & " -vcodec -c libx264 " & movedFileInfo & ".mp4"
psi.ToString()
'proc = Process.Start(psi)
'***convert each MTS file in the new directory to MP4****
'Writes filenames to merge.txt as " path\to\merge.txt , 'file ' F:\path\to\ file1 .MP4 '" so that ffmpeg can merge, then rename
'My.Computer.FileSystem.WriteAllText(new_video_directory & "merge.txt", "file '" & movedFileInfo & ".mp4'" & vbCrLf, True)
'>>>>need to add carriage return to text file
'NOW CAPTURE FILENAMES OF MP4 and MERGE INTO 1 MP4 FILE
' merge all F:\path\to\merge.txt to merge the files & merge them
'psi.Arguments = "ffmpeg -f concat -i " & new_video_directory & "merge.txt -c copy " & new_filename & ".mp4"
proc = Process.Start(psi)
Next
'***END MERGE FILES***
'~~~~~~~~~~~~~~~~~~~~~~~~~~~~* END - MOVE
'***START CREATE STORAGE DIRECTORY STRUCTURE ***
'Verify if the build # directory exists?
If My.Computer.FileSystem.DirectoryExists(dir & Me.BUILD.Text) Then
MessageBox.Show("The build directory exists, moving on to create subdirectories")
Else
Try
'create the new directory F:\ build \ FLIGHT #
My.Computer.FileSystem.CreateDirectory(dir & Me.BUILD.Text)
MessageBox.Show("The build directory" & dir & Me.BUILD.Text & " was created.")
Catch ex As Exception
MessageBox.Show("Doh! The build directory could not be created! Error: " & ex.Message, "Error creating directory.", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
'verify if the flight num directory exists - or create it
If My.Computer.FileSystem.DirectoryExists(new_flightnum_directory) Then
MessageBox.Show("The flight # folder already exists! Check that you have the right Flight #.")
Else
Try
'create the new directory F:\ BUILD \ FLIGHT #
My.Computer.FileSystem.CreateDirectory(new_flightnum_directory)
'Now create new subDirectories
My.Computer.FileSystem.CreateDirectory(new_video_directory)
MessageBox.Show("The new flight directory & video CAM subdirectories have been created! The videos will be moved and files converted now which will take some time.")
Catch ex As Exception
MessageBox.Show("Doh! The flight num or CAM directory could not be created! Error: " & ex.Message, "Error creating directory.", _
MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
'***END CREATE STORAGE DIRECTORY STRUCTURE ***
MessageBox.Show("new merged video file has been created in " & dir & Me.BUILD.Text & "\" & Me.CAM.Text)
End Sub
End Class
The problem is that the & operator in VB is used only to concatenate System.String objects. It's stricter than using + to concatenate. You can't use it to concatenate a String and a System.IO.FileInfo object together. What you want is to get the file name from the FileInfo object. It has an attribute, FileInfo.FullName which will return the full path of the file as a String - from the documentation.
Try instead:
For Each foundFile As String In My.Computer.FileSystem.GetFiles(video_card_dir, Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, "*.MTS")
Dim movedFileInfo As New System.IO.FileInfo(foundFile)
psi.Arguments = "ffmpeg -i " & movedFileInfo.FullName & " -vcodec -c libx264 " & movedFileInfo.FullName & ".mp4"
psi.ToString()
proc = Process.Start(psi)
Next
If you want to replace the .mts extension with .mp4, instead of simply appending .mp4 as this code does, please see this question.

Using replace method to change password

I am using following code to replace the passwords in my app.config. It replaces successfully but does not reload config file in the memory so datasets give error of wrong password.
Please help
Dim vrTextFind As String = "Password"
Dim vrTextReplaceWith As String = "PWD"
Dim path As String = "D:\VS2008\EncTest\EncTest\bin\Debug\enctest.exe.config"
Dim readText As String = File.ReadAllText(path)
TextBox1.Text = readText
'Find
Dim idx As Integer = 0
idx = TextBox1.Text.IndexOf(vrTextFind, idx)
If idx = -1 Then
MessageBox.Show(vrTextFind & " is not in Textbox1")
Else
TextBox1.SelectionStart = idx
TextBox1.SelectionLength = vrTextFind.Length
End If
'Replace
If TextBox1.Text.Contains(TextBox1.Text) Then
TextBox1.Text = TextBox1.Text.Replace(vrTextFind, vrTextReplaceWith)
Else
MessageBox.Show(TextBox1.Text & " is not in Textbox3")
End If
'''''
'Write all back
File.WriteAllText(path, TextBox1.Text)
'Refreshes the connection string section
ConfigurationManager.RefreshSection("connectionStrings")
In windows application app.config is read only once, when the application starts. If you modify it you will need to restart the app.
Suggestion
Instead of storing password in app.config store it in some other file (like Settings file). Which can be modified and read at runtime. For Settings you can read on MSDN. And choose User-Scope settings.
Hope this helps you.
Instead of using File.WriteallText use the following code to write to app.config:
config.AppSettings.Settings.Item("ConnectionString").Value = TextBox1.Text
config.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("AppSettings")
Then again load the connection string value from app.config.
Dim config As System.Configuration.Configuration
Dim fileMap As New ExeConfigurationFileMap()
fileMap.ExeConfigFilename = "Path of app.config"
config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None)
' Sets values to config file.
If config.HasFile() Then
strConnString = config.AppSettings.Settings.Item("ConnectionString").Value
End If