public async Task <string> UploadFileToVm(Guid uuid, string username, string password, string filepath, Stream fileStream) { _logger.LogDebug("UploadFileToVm called"); ManagedObjectReference vmReference = vmReference = await GetVm(uuid); if (vmReference == null) { var errorMessage = $"could not upload file, vmReference is null"; _logger.LogDebug(errorMessage); return(errorMessage); } //retrieve the properties specificied RetrievePropertiesResponse response = await _client.RetrievePropertiesAsync( _props, VmFilter(vmReference)); NetVimClient.ObjectContent[] oc = response.returnval; NetVimClient.ObjectContent obj = oc[0]; foreach (DynamicProperty dp in obj.propSet) { if (dp.val.GetType() == typeof(VirtualMachineSummary)) { VirtualMachineSummary vmSummary = (VirtualMachineSummary)dp.val; //check vmware tools status var tools_status = vmSummary.guest.toolsStatus; if (tools_status == VirtualMachineToolsStatus.toolsNotInstalled || tools_status == VirtualMachineToolsStatus.toolsNotRunning) { var errorMessage = $"could not upload file, VM Tools is not running"; _logger.LogDebug(errorMessage); return(errorMessage); } // user credentials on the VM NamePasswordAuthentication credentialsAuth = new NamePasswordAuthentication() { interactiveSession = false, username = username, password = password }; ManagedObjectReference fileManager = new ManagedObjectReference() { type = "GuestFileManager", Value = "guestOperationsFileManager" }; // upload the file GuestFileAttributes fileAttributes = new GuestFileAttributes(); var fileTransferUrl = _client.InitiateFileTransferToGuestAsync(fileManager, vmReference, credentialsAuth, filepath, fileAttributes, fileStream.Length, true).Result; // Replace IP address with hostname RetrievePropertiesResponse hostResponse = await _client.RetrievePropertiesAsync(_props, HostFilter(vmSummary.runtime.host, "name")); string hostName = hostResponse.returnval[0].propSet[0].val as string; if (!fileTransferUrl.Contains(hostName)) { fileTransferUrl = fileTransferUrl.Replace("https://", ""); var s = fileTransferUrl.IndexOf("/"); fileTransferUrl = "https://" + hostName + fileTransferUrl.Substring(s); } // http put to url using (var httpClientHandler = new HttpClientHandler()) { using (var httpClient = new HttpClient(httpClientHandler)) { httpClient.DefaultRequestHeaders.Accept.Clear(); using (MemoryStream ms = new MemoryStream()) { var timeout = _configuration.GetSection("vmOptions").GetValue("Timeout", 3); httpClient.Timeout = TimeSpan.FromMinutes(timeout); fileStream.CopyTo(ms); var fileContent = new ByteArrayContent(ms.ToArray()); var uploadResponse = await httpClient.PutAsync(fileTransferUrl, fileContent); } } } } } return(""); }