Dim ret As String = ""
Dim output As String = ""
' Run hidden WinSCP process
Dim winscp As Process = New Process()
'Dim logname As String = Path.ChangeExtension(Path.GetTempFileName, "xml")
Dim logname As String = "C:\SFTP\Logs\WinSCP_5_1_1_XML_" & DateTime.Now.ToString("yyyy-MM-dd-hh-mm") & ".xml"

Try

	With winscp.StartInfo
		' SFTPExecutable needs to be defined in app.config to point to winscp.com
		Try
			.FileName = AppDomain.CurrentDomain.BaseDirectory & "WinSCP.com"
			If IsNothing(.FileName) = True Then
				EventLog.WriteEntry("resapp", "ERROR in Function CallWinSCP in Common.vb: The executable file was not found or is incorrectly named. ABORTING!" & _
									"Arguments to Function may follow: command = " & command & " box= " & box & " dir = " & dir & " id = " & id & _
						" pwd = " & pwd & " filename = " & filename & " tempdir = " & tempdir, EventLogEntryType.Error)
				Return "ERROR"
			Else
				If .FileName.Length = 0 Then
					EventLog.WriteEntry("resapp", "ERROR in Function CallWinSCP in Common.vb: The executable file was not found or is incorrectly named. ABORTING!" & _
										"Arguments to Function may follow: command = " & command & " box= " & box & " dir = " & dir & " id = " & id & _
						" pwd = " & pwd & " filename = " & filename & " tempdir = " & tempdir, EventLogEntryType.Error)
					Return "ERROR"
				End If
			End If
			.Arguments = "/xmllog=" + logname
			'
			.UseShellExecute = False
			'
			.RedirectStandardInput = True
			.RedirectStandardOutput = False
			.CreateNoWindow = True

			'.WindowStyle = ProcessWindowStyle.Hidden
		Catch ex As Exception
			EventLog.WriteEntry("resapp", "ERROR in Function CallWinSCP in Common.vb during With winscp.StartInfo: " & ex.Message & " ABORTING!" & _
								"Arguments to Function may follow: command = " & command & " box= " & box & " dir = " & dir & " id = " & id & _
						" pwd = " & pwd & " filename = " & filename & " tempdir = " & tempdir, EventLogEntryType.Error)
			winscp.Dispose()
			Return "ERROR"
		End Try
	End With

	Try
		winscp.Start()
	Catch ex As Exception
		EventLog.WriteEntry("resapp", "ERROR in Function CallWinSCP during winscp.Start in Common.vb: " & ex.Message & " ABORTING!" & _
							"Arguments to Function may follow: command = " & command & " box= " & box & " dir = " & dir & " id = " & id & _
						" pwd = " & pwd & " filename = " & filename & " tempdir = " & tempdir, EventLogEntryType.Error)
		winscp.Dispose()
		Return "ERROR"
	End Try

	' Feed in the scripting commands
	With winscp.StandardInput
		.WriteLine("option batch abort")
		.WriteLine("option confirm off")
		.WriteLine("open sftp://" & id & ":" & pwd & "@" & box & "/ -hostkey=""" & myhostkey & """")
		'.WriteLine("open sftp://" & id & ":" & pwd & "@" & box & "/")
		.WriteLine("cd " & dir)
		Select Case command
			Case "put"
				If IsNothing(filename) = False Then
					If filename <> "" And tempdir <> "" Then
						.WriteLine("put " & """" & tempdir & filename & """")
					End If
				End If
			Case "list"
				If filename = "" Then
					.Write("ls")
				Else
					If filterlist = True Then
						.Write("ls " & filename)
					Else
						.Write("stat " & filename)
					End If                            
				End If
			Case "search"
				.Write("stat " & filename)
			Case "get"
				.WriteLine("lcd " & tempdir)
				.WriteLine("get " & filename)
			Case "delete"
				.WriteLine("rm " & filename)
			Case "trigger"
				.Write("put c:\resapp\empty.txt .chmod_trigger")
			Case Else
				EventLog.WriteEntry("resapp", "ERROR in Function CallWinSCP in Common.vb: The command = " & command & " is unknown to SFTP." & _
						   "Arguments to Function may follow: command = " & command & " box= " & box & " dir = " & dir & " id = " & id & _
					   " pwd = " & pwd & " filename = " & filename & " tempdir = " & tempdir, EventLogEntryType.Error)
		End Select
		.Close()
	End With

	' The OUTPUT has been turned off because of size limit
	'output = winscp.StandardOutput.ReadToEnd()

	' Wait until WinSCP finishes
	winscp.WaitForExit()

	EventLog.WriteEntry("resapp", "INFO: output from Function CallWinSCP in Common.vb: winscp.WaitForExit() was executed...", EventLogEntryType.Information)

	' Parse and interpret the XML log
	' (Note that in case of fatal failure the log file may not exist at all)
	If Not File.Exists(logname) Then
		EventLog.WriteEntry("resapp", "ERROR in Function CallWinSCP in Common.vb: The XML log file for WinSCP was not found during processing." & _
							"Arguments to Function may follow: command = " & command & " box= " & box & " dir = " & dir & " id = " & id & _
						" pwd = " & pwd & " filename = " & filename & " tempdir = " & tempdir, EventLogEntryType.Error)
		winscp.Dispose()
		ret = "ERROR"
	End If

	Dim log As XPathDocument = New XPathDocument(logname)
	Dim ns As XmlNamespaceManager = New XmlNamespaceManager(New NameTable())
	ns.AddNamespace("w", "http://winscp.net/schema/session/1.0")
	Dim nav As XPathNavigator = log.CreateNavigator()

	' Success (0) or error?            
	If winscp.ExitCode <> 0 Then
		If IsNothing(output) = False Then
			If output <> "" Then
				If InStr(UCase(output), "NO SUCH FILE OR DIRECTORY") = 0 Then
					ret = "ERROR"
				Else
					ret = "NOTFOUND"
				End If
			End If
		End If

		' See if there are any messages associated with the error               
		For Each message As XPathNavigator In nav.Select("//w:message", ns)
			EventLog.WriteEntry("resapp", "ERROR in Function CallWinSCP in Common.vb: Message.value from log may follow: " & message.Value & _
				".  Message.InnerXML may follow: " & message.InnerXml & ". Arguments to Function may follow: command = " & command & " box= " & box & " dir = " & dir & " id = " & id & _
				" pwd = " & pwd & " filename = " & filename & " tempdir = " & tempdir, EventLogEntryType.Error)

			If InStr(UCase(message.Value), "NO SUCH FILE OR DIRECTORY") <> 0 Then
				ret = "NOTFOUND"
			End If
			If InStr(UCase(message.InnerXml), "NO SUCH FILE OR DIRECTORY") <> 0 Then
				ret = "NOTFOUND"
			End If
		Next message

	ElseIf winscp.ExitCode = 0 Then
		Select Case command
			Case "put"
				ret = "SUCCESS"
			Case "delete"
				ret = "SUCCESS"
			Case "list"
				If filename = "" Or filterlist = True Then
					Dim mylisting As XPathNodeIterator = nav.Select("//w:file", ns)
					For Each fstring As XPathNavigator In mylisting
						Dim rtype As String = LCase(fstring.SelectSingleNode("w:type/@value", ns).Value)
						Dim rfile As String = UCase(fstring.SelectSingleNode("w:filename/@value", ns).Value)
						Dim modtime As String = fstring.SelectSingleNode("w:modification/@value", ns).Value
						ret = ret & rtype & "," & rfile & "," & modtime & ";"
					Next
				Else
					ret = "SUCCESS"
				End If
			Case "search"
				Dim mylisting As XPathNodeIterator = nav.Select("//w:file", ns)
				For Each fstring As XPathNavigator In mylisting
					Dim rtype As String = LCase(fstring.SelectSingleNode("w:type/@value", ns).Value)                            
					Dim modtime As String = fstring.SelectSingleNode("w:modification/@value", ns).Value
					ret = ret & rtype & "," & filename & "," & modtime
				Next
			Case "get"
				ret = "SUCCESS"
			Case "trigger"
				ret = "SUCCESS"
			Case Else
		End Select
	End If

Catch ex As Exception
	EventLog.WriteEntry("resapp", "ERROR in Function CallWinSCP in Common.vb: " & ex.Message & "StandardOutput (commands) may follow: " & output & _
						"Arguments to Function may follow: command = " & command & " box= " & box & " dir = " & dir & " id = " & id & _
						" pwd = " & pwd & " filename = " & filename & " tempdir = " & tempdir, EventLogEntryType.Error)
	ret = "ERROR"
End Try