I am trying to upload file in web server as following using C#
try
{
// create WebClient object
WebClient client = new WebClient();
string myFile = @"D:\test_file.txt";
client.Credentials = CredentialCache.DefaultCredentials;
// client.UploadFile(@"http://mywebserver/myFile", "PUT", myFile);
client.UploadFile(@"http://localhost/uploads", "PUT", myFile);
client.Dispose();
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
But every time I am getting this error:
The remote server returned an error: (405) Method Not Allowed.
I have solved this using the POST method and server side code:
C# code
try
{
WebClient client = new WebClient();
string myFile = @"D:\test_file.txt";
client.Credentials = CredentialCache.DefaultCredentials;
client.UploadFile(@"http://localhost/uploads/upload.php", "POST", myFile);
client.Dispose();
}
catch (Exception err)
{
MessageBox.Show(err.Message);
}
Server side PHP code upload.php
<?php
$filepath = $_FILES["file"]["tmp_name"];
move_uploaded_file($filepath,"test_file.txt");
?>
The error means that the "PUT" method you are using is not allowed by the server. Check the response headers for allowed methods. More info here.
Or check the documentation for the application to which you are trying to upload the file.
the error is showing that you need to register with the service which you are using
in the case of wcf you can register like this
"%WINDIR%\Microsoft.Net\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe" -r
来源:https://stackoverflow.com/questions/31086117/file-upload-to-web-server-using-c-sharp