Jui Test Jui Test - 10 months ago 54
ASP.NET (C#) Question

How to upload a file from client machin to server by using webservice

How to upload a file from client machin to server by using webservice

I have created webservice using C#.That take filepath/url(object from client pc ,not hosted anywhere),convert to byte array.And using that create a file on server location.Below code working fine on local machine.I uploaded file from C drive to D drive.But when I hosted service on server not localhost and trying to access,file not get uploaded and getting msg like this : Could not find file 'C:\Fileupload\test.txt'..Client can send only url of file that from local machine not hosted anywhere can not send byte array.Is there any option apart from creating new file in server.Can I directly upload like fileuploadcontrol.Client can either use web app or windows app or windows service for uploading

Here is my code :

string uploadFolder = = @"D:\UploadFiles\";

public string UploadFile(string filePath)


byte[] f = System.IO.File.ReadAllBytes(filePath);
MemoryStream ms = new MemoryStream(f);

uploadFolder = uploadFolder + StrFilename;
// StrFilename extracted from filepath

FileStream fs = new FileStream(uploadFolder, FileMode.Create);


return "OK";

catch (Exception ex)
// return the error message if the operation fails
return ex.Message.ToString();


Answer Source

This'll never work.

Your (deployed) web service only has access to the files in it's directory and subdirectories. You can't just pass it any other folder on your laptop, and expect it to be able to read the files in there... that'd be a security nightmare.

If your client application is a webpage, you'd need to have a file upload control, which calls a web service that accepts a stream. In my code, I use the excellent (and free) MultipartParser C# library to help me do this.

Otherwise, there are a huge number of examples out there, which'll show you how to upload files to a web service.

Uploading file using WCF services

By the way, why are you converting a string into a string ?

return ex.Message.ToString();