问题
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.
回答1:
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");
?>
回答2:
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.
回答3:
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
HTTP Error 405 Method not allowed
来源:https://stackoverflow.com/questions/31086117/file-upload-to-web-server-using-c-sharp