Search code examples
c#winformsweb-servicesasmx

Upload a File using a Windows Forms to a ASP.NET Web Service (ASMX)


I want to upload a file using windows application to a web service so that web service can process the file.

Please tell me how can i achieve this.

I only know that i can use web service with windows forms to send only string, int, these types. But what about file.

Any help is appreciated


Solution

  • As Will Wu said you can always declare a web method that takes a byte[] as input in your web service, but if you don't like to send the byte array as it is in your web service call, you can always encode the byte[] to a base64 string from your client and decode the byte[] on the server side

    Example

    WebService sample web Method

        [WebMethod]
        public bool UploadFile(string fileName, string uploadFileAsBase64String)
        {
            try
            {
                byte[] fileContent = Convert.FromBase64String(uploadFileAsBase64String);
    
                string filePath = "UploadedFiles\\" + fileName;
                System.IO.File.WriteAllBytes(filePath, fileContent);
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    

    Client Side Base64 string generation

        public string ConvertFileToBase64String(string fileName)
        {
            byte[] fileContent = System.IO.File.ReadAllBytes(fileName);
            return Convert.ToBase64String(fileContent);
        }
    

    use the above method to convert your file to a string and send it to the web service as a string instead of byte array