VB.NET System.IO.File.Copy question - vb.net

I'm using System.IO.File.Copy to copy a file to c$ on a remote server. I need to specify username/password for the connection. Is there a simple way to do this? I had hoped that System.IO.File.Copy would accept credentials as an argument but it doesn't. How can I do this?

You cant add credentials to the system.io.file but there seems to be a workaround here:
http://forums.asp.net/t/1283577.aspx/1
Snippet from above link:
using (System.Security.Principal.WindowsImpersonationContext ctx = System.Security.Pricipal.WindowsIdentity.Impersonate(userTokenptr))
{
//do your IO operations
ctx.Undo();
}
Converted to vb.net:
Using ctx As System.Security.Principal.WindowsImpersonationContext = System.Security.Pricipal.WindowsIdentity.Impersonate(userTokenptr)
'do your IO operations
ctx.Undo()
End Using
Credits goes to Ganeshyb

Absolute simplest thing to do is to add this routine to your code then call it right before your File.Copy:
Private Sub Open_Remote_Connection(ByVal strComputer As String, ByVal strUsername As String, ByVal strPassword As String)
'//====================================================================================
'//using NET USE to open a connection to the remote computer
'//with the specified credentials. if we dont do this first, File.Copy will fail
'//====================================================================================
Dim ProcessStartInfo As New System.Diagnostics.ProcessStartInfo
ProcessStartInfo.FileName = "net"
ProcessStartInfo.Arguments = "use \\" & strComputer & "\c$ /USER:" & strUsername & " " & strPassword
ProcessStartInfo.WindowStyle = ProcessWindowStyle.Hidden
System.Diagnostics.Process.Start(ProcessStartInfo)
'//============================================================================
'//wait 2 seconds to let the above command complete or the copy will still fail
'//============================================================================
System.Threading.Thread.Sleep(2000)
End Sub

Related

File Download via shdocvw.dll with custom headers

I need to download a really large file in msaccess via a vba application.
Using the objects MSXML2.ServerXMLHTTP.6.0 and WinHttp.WinHttpRequest.5.1 result in an error stating that there is not enough storage available to complete this operation. Therefore i resorted in using the DoFileDownload method from shdocvw.dll.
What i want to do is pass an extra header (an API key) to the request sent by the function.
Here is roughly what i want to do.
Private Declare Function DoFileDownload Lib "shdocvw.dll" _
(ByVal lpszFile As String) As Long
Public Sub Download()
sDownloadFile = StrConv(<link_to_download>, vbUnicode)
'set a header before calling DoFileDownload
Call DoFileDownload(sDownloadFile)
End Sub
How do i approach this problem?
A WebRequest downloading a whole file at once stores the whole data in response.
Although there are options to chunk response, using Wget is less coding, but more options.
Private Sub DownloadFileWget()
Const PathToWget As String = "" 'if wget is not in path use "Path\To\Wget"
Dim LinkToFile As String
Dim SavePath As String
With CreateObject("WScript.Shell")
LinkToFile = "http://download.windowsupdate.com/microsoftupdate/v6/wsusscan/wsusscn2.cab" 'huge file > 500MB
SavePath = "C:\doc" 'folder to save download
.CurrentDirectory = SavePath
.Run Chr(34) & PathToWget & "wget.exe" & Chr(34) & " --header='name: value' " & Chr(34) & LinkToFile & Chr(34) & " -N", 1, True
' -N: Continue download only if the local version is outdated.
End With
End Sub

"Attempted to perform an unauthorized operation" error when using Registry.SetValue

I attempted to make a program in VB.NET that would add itself to startup in the Windows registry. However, when I run the program I receive this error message:
Attempted to perform an unauthorized operation.
I have attempted to change permissions and used many methods online but they all proved to be unsuccessful. I just do not seem to have the permission to interfere in the registry.
Here is my code:
My.Computer.Registry.SetValue("HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run", "FILENAME", "FILEPATH")
What am I doing wrong?
As Joel stated in the comments, you should open the subkey first, and then set the value.
Here's the methods I usually use to add/remove my programs to/from Windows startup:
Public Sub AddToStartup(Optional appCommand As String = "")
Dim applicationName As String = Application.ProductName
Dim applicationPath As String = Application.ExecutablePath
Dim regKey As Microsoft.Win32.RegistryKey
regKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True)
regKey.SetValue(applicationName, """" & applicationPath & """" & appCommand)
regKey.Close()
End Sub
Public Sub RemoveFromStartup()
Dim applicationName As String = Application.ProductName
Dim regKey As Microsoft.Win32.RegistryKey
regKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True)
regKey.DeleteValue(applicationName, False)
regKey.Close()
End Sub
I use an Optional parameter (i.e., appCommand) in AddToStartup method in case I wanted to pass a command argument to the instance that runs at Windows startup. For example " -Hide" to hide the program in tray when running at startup.
Side note: always give the user the option to willingly add your application to startup, and the option to reverse that. Do not force your application to run at startup without the user's permission, otherwise the user will hate you :)

Outlook External Application/Service Start

Is there any way to have outlook start an external application or service based on an outlook calendar task, event, appointment? Also if so, is there a way to get it to pass parameters to it?
Yes you can do this using the Shell method.
Private Sub TestAcrobatReader()
Const strcProgramName As String = _
"C:\Program Files\Adobe\Reader 9.0\Reader\AcroRd32.exe"
Const strcFilePath As String = _
"C:\Program Files\Adobe\Reader 9.0\Reader\plug_ins\" _
& "Annotations\Stamps\Words.pdf"
Dim dblProgTaskID As Double
Dim strPathName As String
strPathName = strcProgramName & " " & strcFilePath
dblProgTaskID = Shell(strPathName, vbMaximizedFocus)
MsgBox "Program Task ID: " & dblProgTaskID
End Sub
Code borrowed from here. You can pass additional parameters by concatenating them on the strPathName.
For automating based on Outlook Calendar there is a wealth of information here.

Running a .bat in the background

So I have this in my coding:
vb Code:
file = My.Computer.FileSystem.OpenTextFileWriter("c:\command.bat", False)
file.WriteLine("#echo off")
file.WriteLine("cd " & TextBox2.Text)
file.WriteLine("adb shell dumpsys meminfo " & TextBox1.Text & " > C:\Sample.txt")
file.Close()
Shell("C:\command.bat")
what I want it to do is to run the batch file without it opening if that makes sense. Right now this runs on a loop for 10 minutes and on every 2 second tick it opens and then closes the .bat. Which is really annoying to see a .bat open and close every two seconds. Is there anyway to get this process to run silently in the background so the user doesnt even know that it is running?
Shell("C:\command.bat", AppWinStyle.Hide)
That will run the batch file but the window is hidden.
or use Process.Start as suggested by David. with WindowStyle = ProcessWindowStyle.Hidden
Here is an example on how to use Process.Start with a hidden window
Dim params As String = "C:\command.bat"
Dim myProcess As New ProcessStartInfo
myProcess.FileName = "cmd.exe"
myProcess.Arguments = params
myProcess.WindowStyle = ProcessWindowStyle.Hidden
Process.Start(myProcess)
if you run into the issue of file not found errors with the path you can try to add the following Windows API call and run your file path through this function as well.
'This would be declared at the top of your Form Code/Class Code
Private Declare Auto Function GetShortPathName Lib "kernel32" ( _
ByVal lpszLongPath As String, _
ByVal lpszShortPath As StringBuilder, _
ByVal cchBuffer As Integer) As Integer
And here is the function to return back a ShortPath (win98 style path (ie. c:/progra~1/myfolder/myfile.bat)
Public Function GetShortPath(ByVal longPath As String) As String
Dim requiredSize As Integer = GetShortPathName(longPath, Nothing, 0)
Dim buffer As New StringBuilder(requiredSize)
GetShortPathName(longPath, buffer, buffer.Capacity)
Return buffer.ToString()
End Function
then simply call your path like this in your process.start function
Dim params As String = GetShortPathName("C:\command.bat")

Windows Service not able to access mapped folders

I have a very simple VB.net Windows Service written using VS.net 2008. The program after doing several other functions writes a log in one of the network folders. The code is as shown below: If I change the path from "Y:\Activity_Log" to "C:\Activity_Log" it is working like a charm.
What is the problem if I use Y drive which is a valid one and I am able to access it from other VB.net desktop apps. Please help.
Dim strFile As String = "Y:\Activity_Log\" & DateTime.Today.ToString("dd-MMM-yyyy") & ".txt"
Dim fs As FileStream = Nothing
Dim activityfolder As String = "Y:\Activity_Log"
Dim di As System.IO.DirectoryInfo
di = New System.IO.DirectoryInfo(activityfolder)
If (Not di.Exists) Then
di.Create()
End If
If (Not File.Exists(strFile)) Then
Try
Dim sw1 As New StreamWriter(File.Open(strFile, FileMode.OpenOrCreate))
sw1.WriteLine("******************************Activity Log for " & Now.Date & "*******************")
sw1.WriteLine("-----------------------------------------------------------------------------------------------------------------")
sw1.WriteLine(Remarks & " ---" & DateTime.Now)
sw1.Close()
Catch ex As Exception
End Try
Else
Dim sw As StreamWriter
sw = AppendText(strFile)
sw.WriteLine(Remarks & " ---" & DateTime.Now)
sw.Close()
End If
Start->Control Panel->Administrative Tools->Services
Find Your service in the list, right click on the name, Properties
Click the Log On tab
Change from Local System account to 'This Account'
Use a user that has access to that share, start with your username/password to convince yourself that it works ;)
Click Ok, then restart the service.
maybe you need to run the service under a user that has access to that drive?
maybe the generic service user doesn't have access.