string filePath = "C:\\test\\564.flv";
try
{
WebClient client = new WebClient();
NetworkCredential nc = new NetworkCredential(uName, password);
Uri addy = new Uri("\\\\192.168.1.28\\Files\\test.flv");
client.Credentials = nc;
byte[] arrReturn = client.UploadFile(addy, filePath);
Console.WriteLine(arrReturn.ToString());
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
i am get this error "The remote server returned an error: (405) Method Not Allowed." what should i doo ??
WebClient uses POST method to upload a file in an HTTP server or uses STOR command to upload a file in an FTP server. It can't upload files in a network folder.
I do not believe the UploadFile() method can have a UNC address for the URI. See the documentation for the method: http://msdn.microsoft.com/en-us/library/ms144229.aspx. It needs to either be an FTP site or an HTTP site.
Related
I have an annoying problem preventing me to get a file I need in an FTP. This file may have differents names so I need to access the folder first and list files inside to do a request directly to the file then.
My problem is that I can access this file in Filezilla for example, and perfectly discovers the folder as well, but when using an FtpWebResponse instance to get the folder, I have an error 550
550 File unavailable (e.g. file not found, no access)
here is the code :
FtpWebRequest wr = (FtpWebRequest)WebRequest.Create("ftp://ftp.dachser.com/data/edi/kunden/da46168958/out");
wr.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
wr.Credentials = new NetworkCredential("login", "password");
FtpWebResponse response = (FtpWebResponse)wr.GetResponse();
Stream reponseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(reponseStream);
string names = reader.ReadToEnd();
FtpWebResponse response = (FtpWebResponse)wr.GetResponse();
is the line throwing the error
PS: Production, tests and FileZilla are on the same domain, using the same internet connection (if it helps)
Thanks for your attention and feedback
The FileZilla logs:
Logs from my program, error circled in red isn't related to FTP error
When FtpWebRequest interprets the URL, it does not consider the slash that separates the hostname and the path as a part of the path. The extracted path is then used with FTP CWD command as is. That means that the FTP server will resolve the path relatively to your home directory. If your account is not chrooted (the home is not seen as the root by the client), the lack of the leading slash leads to unexpected behaviour.
In your case, you start in /remote/path and with URL like ftp://example.com/remote/path/, it will try to change to remote/path, so ultimately to /remote/path/remote/path. That's not what you want.
Either you must use a relative path to the home folder. What in your case means using an URL without any path.
Or use an absolute path, for which you need to use two slashes after the hostname: ftp://example.com//remote/path/.
Also note that an URL to a folder should end with a slash: Why does FtpWebRequest return an empty stream for this existing directory?
For other 550 problems, see FtpWebRequest returns error 550 File unavailable
In 2021 this works on both our Linux and Windows live boxes reading from ftp server (both on Windows and Linux)
Note
the main folder on the Windows ftp is web
the main folder on the Linux ftp is public_html
TL;DR;
bottom line: the URL needs to be ended with /
It works:
ftp://ftp.yourdomain.com.br/public_html/
ftp://ftp.yourdomain.com.br//public_html/
ftp://ftp.yourdomain.com.br/web/
ftp://ftp.yourdomain.com.br//web/
It doesn't work:
ftp://ftp.yourdomain.com.br/public_html
ftp://ftp.yourdomain.com.br//public_html
ftp://ftp.yourdomain.com.br/web
ftp://ftp.yourdomain.com.br//web
Usage:
//verifiy if the directory public_html does exists
var url = "/public_html/";
var result = FtpUtil.DoesDirectoryExists(url, "ftp://ftp.yourdomain.com.br", "ftp user here", "ftp password here");
static bool DoesDirectoryExists(string directory, string ftpHost, string ftpUser, string ftpPassword) {
FtpWebRequest ftpRequest = null;
try {
ftpRequest = (FtpWebRequest)WebRequest.Create(new Uri("ftp://" + ftpHost + directory));
ftpRequest.Credentials = new NetworkCredential(ftpUser, string ftpPassword);
ftpRequest.UseBinary = true;// optional
ftpRequest.KeepAlive = false;// optional
ftpRequest.UsePassive = true;// optional
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
using (FtpWebResponse response = (FtpWebResponse)ftpRequest.GetResponse()) {
return true;//directory found
}
}
catch (WebException ex) {
if (ex.Response != null) {
FtpWebResponse response = (FtpWebResponse)ex.Response;
if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
return false;// directory not found.
}
return false; // directory not found.
}
finally {
ftpRequest = null;
}
}
I am trying with below code, to Upload a document in remote server, but it shows an Error "The given path's format is not supported."
using (WebClient client = new WebClient())
{
client.Credentials = new NetworkCredential(UserName, Password);
Directory.CreateDirectory(#"https://Sample.com/Folders/Test Folder/"); //Error shown here
client.UploadFile("https://Sample.com/Folders/Test Folder/", "POST" , #"C:\\Sample Document.docx");
}
How can I create the necessary directories with webclient ?
You could try like below
//File Path
string filepath = System.Web.HttpContext.Current.Server.MapPath("~/Folders/Test Folder/");
if (!Directory.Exists(filepath))
{
Directory.CreateDirectory(filepath);
}
I am uploading a file with C# code on php server. But facing some issues.
First I was using a WebClient Object to upload file by calling UploadFile() method, and uploading string to by calling UploadString() method by following code:
String StoreID = "First Store";
WebClient Client = new WebClient();
String s = Client.UploadString("http://localhost/upload.php", "POST", StoreID);
Client.Headers.Add("Content-Type","binary/octet-stream");
byte[] result = Client.UploadFile("http://localhost/upload.php", "POST", "C:\\aaaa.jpg");
s = s + System.Text.Encoding.UTF8.GetString(result,0,result.Length);
Issue is that I am requesting two times so string and file is not being send at same time. I am receiving either String or File. But I need both at same time. I don't want to use UploadData() becuase it will use byte codes and I have know I idea how to extract it in php.
Let that string is folder name, i have to send string and file, so that file could save at specified folder at php server.
I studied there may be a solution with WebRequest and WebResponse object. But dont know how to send request using WebResponse by C# and get it at PHP.
Any Suggestions!!!!
Try this :
WebClient web = new WebClient();
try{
web.UploadFile("http://" + ip + "/test.php", StoreID);
}
catch(Exception e)
{
MessageBox.Show("Upload failed");
}
Now you can access the file from the PHP file.
<?php
//check whether the folder the exists
if(!(file_exists('C:/Users/dhanu-sdu/Desktop/test')))
{
//create the folder
mkdir('C:/Users/ComputerName/Desktop/test');
//give permission to the folder
chmod('C:/Users/ComputerName/Desktop/test', 0777);
}
//check whether the file exists
if (file_exists('C:/Users/ComputerName/Desktop/test/'. $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
//move the file into the new folder
move_uploaded_file($_FILES["file"]["tmp_name"],'C:/Users/ComputerName/Desktop/test/'. $_FILES["file"]["name"]);
}
?>
Also, you can download data from a PHP server and display it in a C# web browser by using the following codes :
WebClient web = new WebClient();
try{
byte[] response = web.DownloadData("http://" + ip +"/test.php");
webBrowser1.DocumentText = System.Text.ASCIIEncoding.ASCII.GetString(response);
}
catch(Exception e)
{
MessageBox.Show("Download failed");
}
You can create a webservice with php that accepts a file. Then publish that webservice, and add it to you c# references, then just call teh method from within your c# code that accepts the file, and vualá!
How to create SOAP with php link
I found a lot of question about (401) Unauthorized error, but none of them explained to me how to diagnose the issue.
I created a new MVC ASP.net app to learn how to upload a file to a sharepoint folder. As of right now, I can't seem to be able to copy a file from
C:\testfolder\file.txt to
C:\testfolder\UploadedFiles
Here is the method that I made where I send in the source file path and the target folder:
//Flag to indicate whether file was uploaded successfuly or not
bool isUploaded = true;
try
{
// Create a PUT Web request to upload the file.
WebRequest request = WebRequest.Create(targetDocumentLibraryPath);
//Set credentials of the current security context
request.PreAuthenticate = true;
request.UseDefaultCredentials = true;
ICredentials credentials = new NetworkCredential( "Username", "password", "Domain"); //I used my username and password here
request.Credentials = credentials;
//request.Credentials = CredentialCache.DefaultCredentials;
request.Method = "PUT";
// Create buffer to transfer file
byte[] fileBuffer = new byte[1024];
// Write the contents of the local file to the request stream.
using (Stream stream = request.GetRequestStream())
{
//Load the content from local file to stream
using (FileStream fsWorkbook = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read))
{
//Get the start point
int startBuffer = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length);
for (int i = startBuffer; i > 0; i = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length))
{
stream.Write(fileBuffer, 0, i);
}
}
}
// Perform the PUT request
WebResponse response = request.GetResponse();
//Close response
response.Close();
}
catch (Exception ex)
{
//Set the flag to indiacte failure in uploading
isUploaded = false; //The remote server returned an error: (401) Unauthorized.
}
//Return the final upload status
return isUploaded;
}
I tried the following:
Changing the permission of the folders to be able to write/read from them for all users.
Use other folder locations (SharePoint, local drive, network drive) to upload the file to.
Any idea on how to get this problem to work? Any prospective on how to debug the problem is also appreciated.
Update: It is probably being my account is set as the app pool account in IIS. I am still not sure what the issue is.
This wouldn't be something like the proxy settings would it?
Do you need to add the default proxy setting to your
WebRequest
Also do you need to add
<system.net>
<defaultProxy useDefaultCredentials="true" />
</system.net>
To your web config?
This may help.
How should I set the default proxy to use default credentials?
I decided to try another approach and use httpposted file and .saveAs() described here
I'm trying to download a file from a url. I try two approachs but it isn't working with external files.
I think it's happening because I have internet over proxy. I can download internal network files (images, mp3, mp4, whatever...) but when I try to download something in external network it gives me timeout or 404 Not Found.
1st approach: System.Net.WebResponse, System.IO.FileStream
try
{
var credentials = new NetworkCredential("myNetworkUserName", "myNetworkPassword", "myNetworkDomain");
var proxy = WebProxy.GetDefaultProxy(); //new WebProxy("myNetworkProxy") <-- I TRY BOOTH WAYS
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://farm1.static.flickr.com/83/263570357_e1b9792c7a.jpg"); //External image link
proxy.Credentials = credentials;
request.Proxy = proxy;
responseExternalImage = request.GetResponse();//explode here ex=""Unable to connect to the remote server""
string fileName = GetFileName(response.ResponseUri.OriginalString);
Stream stream = response.GetResponseStream();
using (BinaryReader br = new BinaryReader(stream))
{
content = br.ReadBytes(50000000);//perto de 50Mb
br.Close();
}
response.Close();
FileStream fs = new FileStream(pathToSaveFile + "\\" + fileName, FileMode.Create);
BinaryWriter bw = new BinaryWriter(fs);
try
{
bw.Write(content);
}
finally
{
fs.Close();
bw.Close();
}
}
catch (Exception ex)
{
}
The exception caught at GetResponse() says: "Unable to connect to the remote server", ""A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 77.238.160.184:80""
2nd approach: System.Net.WebClient, DownloadFile
try
{
var credentials = new NetworkCredential("xpta264", ConfigurationManager.AppSettings["Xpta264Password"], "ptsi");
var proxy = WebProxy.GetDefaultProxy();
proxy.Credentials = credentials;
// Create a new WebClient instance.
using (WebClient myWebClient = new WebClient())
{
myWebClient.Proxy = proxy;
// Download the Web resource and save it into the current filesystem folder.
myWebClient.DownloadFile("http://farm1.static.flickr.com/83/263570357_e1b9792c7a.jpg", pathToSaveFile + "\\testImage.jpg");
}
}
catch (Exception e)
{
}
The exception was caught at DownloadFile method and gives me the same error.
Hope someone can help me.
Sorry for my English
WebProxy.GetDefaultProxy() is obsolete and doesn't handle all cases. From the docs:
Note: This API is now obsolete.
The GetDefaultProxy method does not pick up any dynamic settings that
are generated from scripts run by Internet Explorer, from automatic
configuration entries, or from DHCP or DNS lookups.
Applications should use the WebRequest.DefaultWebProxy property and
the WebRequest.GetSystemWebProxy method instead of the GetDefaultProxy
method.
A better approach is to try to request a url and see if a proxy was used. I use this code in my own production system and it seems to work pretty well. Once you find the proxy, you can cache the address somewhere:
WebProxy proxy = null;
Uri testUri = new Uri("http://www.example.com/"); // replace with REAL url
Uri proxyEndpoint = WebRequest.GetSystemWebProxy().GetProxy(testUri);
if (!testUri.Equals(proxyEndpoint))
proxy = new WebProxy(proxyEndPoint.ToString());
You can also just try calling WebRequest.GetSystemWebProxy() and see if that gives you the proxy, but I remember having problems with that which is why I went the request route above. YMMV.