Click here to Skip to main content
15,887,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
C#
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


What I have tried:

C#
Here is my code :

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

[WebMethod]
public string UploadFile(string filePath)
{

try
{

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);

ms.WriteTo(fs);
ms.Close();
fs.Close();
fs.Dispose();

return "OK";
}

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

}
Posted

1 solution

It worked on your local machine as the client and server are the same machine so when the client sends "c:\file.txt" that file can be read in your server code. When you deploy your site the client and server are different machines so when you send "c:\file.txt" that file does not exist on the server so it can't read it. Remember that your .net code isn't running on the client machine in the browser so it can't access the client file system, it would be a huge security concern if it could.

Google how to upload a file to a web service, the specifics depend on what you're doing but ultimately you'll need an input control of type "file" and either post that to your web service or serialise it via the html5 file api and post it to the web service that way. As I said, google for exact code, but what you're doing now simply isn't going to work.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900