I am trying to connect to an FTP server to upload a file. I am getting the "
Unable to connect" error. If I use command line and open an FTP connection, I am able to connect. Not sure why I get error when connecting programatically. Any help will surely be appreciated.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://1.23.84.2");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = new NetworkCredential("user","password");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader(path);
byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}",
response.StatusDescription);
response.Close();
So after a few hours of trouble shooting, It was McAfee blocking the ftp port. had to temporarily disable the services on a local machine.
I think the FtpWebReqest needs to point to the target path, not just the server's address, like the following:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://1.23.84.2/myFile.zip");
The correct usage for FTP uploads in context of FtpWebRequest can be found here.
Related
I am using below code (C# .NET 3.5) to upload a file:
FtpWebRequest request =
(FtpWebRequest)WebRequest.Create("ftp://someweb.mn/altanzulpharm/file12.zip");
request.Method = WebRequestMethods.Ftp.UploadFile;
request.KeepAlive = true;
request.UseBinary = true;
request.Credentials = new NetworkCredential(username, password);
FileStream fs = File.OpenRead(FilePath);
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
fs.Close();
Stream ftpstream = request.GetRequestStream();
ftpstream.Write(buffer, 0, buffer.Length);
ftpstream.Close();
But the upload breaks when internet interrupted. Interruption occurs for a very small amount of time, almost a millisecond. But uploading breaks forever!
Is it possible to continue or resume uploading after interruption of internet?
I don't believe FtpWebRequest supports re-connection after losing connection. You can resume upload from given position if server supports it (this support is not required and presumably less common that retry for download).
You'll need to set FtpWebRequet.ContentOffset upload. Part of sample from the article:
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(serverUri);
request.ContentOffset = offset;
Internal details of restore in FTP protocol itself - RFC959: 3.5 - Error recovery and restart. Question showing retry code for download - Downloading from FTP with c#, can't retry when fail
The only way to resume transfer after a connection is interrupted with FtpWebRequest, is to reconnect and start writing to the end of the file.
For that use FtpWebRequest.ContentOffset.
A related question for upload with full code (although for C#):
How to download FTP files with automatic resume in case of disconnect
Or use an FTP library that can resume the transfer automatically.
For example WinSCP .NET assembly does. With it, a resumable upload is as trivial as:
// Setup session options
var sessionOptions = new SessionOptions
{
Protocol = Protocol.Ftp,
HostName = "ftp.example.com",
UserName = "user",
Password = "mypassword"
};
using (var session = new Session())
{
// Connect
session.Open(sessionOptions);
// Resumable upload
session.PutFileToDirectory(#"C:\path\file.zip", "/home/user");
}
(I'm the author of WinSCP)
I am new to .net and APIs and am currently using .Net 4.5 to connect to an API using rest. The problem I am having is I get an exception thrown back in the return xml that says "Cannot forward request to server with name", "Cannot read data from connection", Connection reset", full error below.
What is odd is this script works fine on smaller datasets but when the response is large enough, I get that exception from the server thrown back. What has helped setting the keep alive to true, using httpversion10, and specifying gzip and sendchunked. I am using advanced rest client to test the server in chrome addins and it returns data fine on there with these larger dataset. It will not with the script below. I am suspecting there is a difference in the way I am telling the server to handle my response verses the chrome add in. Any suggestions on how I improve the performance of this?
This is what the advanced rest client settings look like that work for the Chrome add in.
This is the code I have which appears to need changes to make it handle the request/response better.
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(#"magicalwebsite");
req.KeepAlive = true;
req.ProtocolVersion = HttpVersion.Version10;
req.ServicePoint.ConnectionLimit = 24;
req.Timeout = 2000000000;
req.Method = "Post";
req.Accept = "*/*";
req.SendChunked = true;
req.AutomaticDecompression = DecompressionMethods.GZip;
//Xml request file for data
string postData = System.IO.File.ReadAllText(#"C:\Users\yo\Desktop\testtest.txt");
//sending header and content
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
req.ContentType = "text/xml";
req.ContentLength = byteArray.Length;
req.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.Default.GetBytes("xxxx:xxxxx"));
Stream dataStream = req.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
//Requesting response of data
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
//Grabbing response
using (Stream stream = resp.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
String responseString = reader.ReadToEnd();
}
This is the exception I am getting in the xml being thrown back.
<?xml version="1.0" encoding="UTF-8"?>
<response success="false">
<messages>
<message key="exception-caught">Caught Exception: Caught Exception:
Cannot forward request to server with name=prod-euapp01
com.magicalpony.exception.APException: Cannot forward request to server with name=prod-euapp01
at com.magicalpony.webservices.APIForwarder.forward(APIForwarder.java:105)
at com.magicalpony.webservices.APIServlet.forwardRequest(APIServlet.java:270)
at com.magicalpony.webservices.APIServlet.wrongServer(APIServlet.java:253)
at com.magicalpony.webservices.APIServlet.service(APIServlet.java:124)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:304)
at org.apache.catalina.core.ApplicationFilterChain.doFilter
(ApplicationFilterChain.java:210)
at com.magicalpony.system.WebServiceMonitor.doFilter(WebServiceMonitor.java:61)
at org.apache.catalina.core.
ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at com.magicalpony.system.HitTracer.doFilter(HitTracer.java:133)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:240)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:164)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:462)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:164)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:563)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:399)
at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:303)
at org.apache.coyote.ajp.AjpProtocol$AjpConnectionHandler.process(AjpProtocol.java:183)
at org.apache.coyote.ajp.AjpProtocol$AjpConnectionHandler.process(AjpProtocol.java:169)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:311)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.magicalpony.exception.APException:
Cannot read data from connection
at com.magicalpony.webservices.NetUtil.readData(NetUtil.java:61)
at com.magicalpony.webservices.APIForwarder.forward(APIForwarder.java:102)
... 26 more
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:196)
at
java.net.SocketInputStream.read(SocketInputStream.java:122)
at java.io.BufferedInputStream.fill(BufferedInputStream.java:235)
at java.io.BufferedInputStream.read1(BufferedInputStream.java:275)
at java.io.BufferedInputStream.read(BufferedInputStream.java:334)
at sun.net.www.http.HttpClient.parseHTTPHeader(HttpClient.java:687)
at sun.net.www.http.HttpClient.parseHTTP(HttpClient.java:633)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1323)
at com.magicalpony.webservices.NetUtil.readData(NetUtil.java:58)
... 27 more</message>
</messages>
</response>
The problem is with DNS resolution.
Step 1: Enter your domain name in a browser and see if Server is available.
Step 2: If server is available with domain name then you got to fix the IP Address or DNS resolution.
You can fix this by updating the IP Address in your PC (Follow steps below)
Go to a folder: C:\Windows\System32\drivers\etc
Copy and paste "hosts" file to desktop.
Update your host file with your IP Address and domain name.
Step 3: Copy and Paste hosts file in original folder (C:\Windows\System32\drivers\etc).
Step 4: Test your API.
I am trying to download a file using FTP through a FTP proxy (on my side).
This is script I am trying to implement in C#:
On Commandline:
ftp -i -s:get.ini CORPORATE_PROXY.com
-----------get.ini------------
CORPORATE_PROXY_USER#CLIENT_FTP.com abc/user_name
CORPORATE_PROXY_PASSWORD
user_name_password
cd pub/linux/knoppix
get packages.txt
bye
-----------get.ini------------
abc/user_name is my user name who was granted by permissions to FTP through my corporate proxy.
I want to implement above script in C#, but after playing with many types of code found on Internet I cannot do that.
FtpWebRequest request = FtpWebRequest.Create(new Uri(#"ftp://" + CORPORATE_PROXY.com + #"/" + Path.GetFileName(fileToUpload))) as FtpWebRequest;
request.UseBinary = true;
request.KeepAlive = false;
request.Method = WebRequestMethods.Ftp.UploadFile;
if (!string.IsNullOrEmpty(CORPORATE_PROXY_USER) && !string.IsNullOrEmpty(CORPORATE_PROXY_PASSWORD ))
request.Credentials = new NetworkCredential(CORPORATE_PROXY_USER, CORPORATE_PROXY_PASSWORD );
//Get physical file
FileInfo fi = new FileInfo(fileToUpload);
Byte[] contents = new Byte[fi.Length];
//Read file
FileStream fs = fi.OpenRead();
fs.Read(contents, 0, Convert.ToInt32(fi.Length));
fs.Close();
request.Proxy = new WebProxy("CLIENT_FTP.com");
request.Proxy.Credentials = new NetworkCredential(abc/user_name, user_name_password);
//Write file contents to FTP server
Stream rs = request.GetRequestStream();
rs.Write(contents, 0, Convert.ToInt32(fi.Length));
rs.Close();
FtpWebResponse response = request.GetResponse() as FtpWebResponse;
string statusDescription = response.StatusDescription;
response.Close();
return statusDescription;
The main problem is that for the proxy I am using WebProxy, while I suspect I should use FTPProxy - which I cannot find anythere? Any ideas which direction should I go, or maybe WebProxy is fine?
In the past I have used Indy Project to get through FTP proxies.
Try using WebRequest instead of FtpWebRequest in your code example.
By doing so, the connection from client to proxy can be HTTP whereas the connection from proxy to destination server is FTP. The proxy will handle the protocol translation, this technique is referred to as FTP over HTTP.
It is also possible to use a native FTP Proxy where client to proxy and proxy to server connections are FTP. Make sure your proxy supports this.
The proxy offers a separate proxy port to serve native FTP proxy connections.
I read documentation of Salesforce Chatter REST API and started to implement code in c#.
See following code:
System.Net.WebRequest req = System.Net.WebRequest.Create(URI);
req.Method = "POST";
req.Headers.Add("Authorization: OAuth " + accessToken);
req.ContentType = "application/x-www-form-urlencoded";
string par =
"fileName=" + fileName +
"&feedItemFileUpload="
+ #"D:\\MyFiles\\NewTextDocument.txt" +
"&desc=" + desc+
"&text=" + text;
byte[] byteArray = Encoding.UTF8.GetBytes(par);
req.ContentLength = byteArray.Length;
Stream dataStream = req.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
System.Net.WebResponse resp = req.GetResponse();
I am gettig error on response
The remote server returned an error: (400) Bad Request.
If i see response of error, i got following message:
Please specify a file to upload. Type in the path to the file, or use the \"Browse\" button to locate it in your local filesystem.
I have already defined the file path and name. I tried with and without # sign before path string but getting same error. Let me know if anything is missing.
You can easily use Fiddler to see what's going on.
You are posting a simple form where fileName and feedItemFileUpload are just like desc and text, in other words, plain simple text!
What you need to do is send the file as a stream.
I can see that you're using Hanselman's code, but that's only for text parameters
for more information on using it for files, see this answer
Upload files with HTTPWebrequest (multipart/form-data)
I have a requirement of transferring a document file (.txt, .xls, .doc, .bmp, .jpg etc) from one server to another server. Both servers are at different locations. My main application is running on second server. And I have to deploy this functionality on the first server from where the files in any fixed folder (say D:\documents) will be transferred to second server periodically at any timer event.
I am using a code like as follows
WebClient wc = new WebClient();
wc.UploadFile("ftp://1.23.153.248//d://ftp.bmp",
#"C:\Documents and Settings\varun\Desktop\ftp.bmp");
I am getting the error as
unable to connect to remote server
or
sometime underlying connection was closed
Could you tell me what's wrong.
The URI of your FTP location seems to be off: you shouldn't have to double all the forward slashes, and I don't think drive letters are supported.
If you do:
WebClient wc = new WebClient();
wc.UploadFile("ftp://1.23.153.248/ftp.bmp",
#"C:\Documents and Settings\varun\Desktop\ftp.bmp");
The file will be sent to the directory set as the FTP location for the anonymous user. If you configure the FTP service on 1.23.153.248 so that location is D:\, everything should work as planned.
Is your ftp public? if no you should define credentials like this
wc.Credentials = new NetworkCredential ("username","password");
before sending file, and try to remove d: from ftp path. ftp clients don't have to know where on server files should be saved... shortly try this
WebClient wc = new WebClient();
wc.Credentials = new NetworkCredential ("username","password");
wc.UploadFile("ftp://1.23.153.248/ftp.bmp", #"C:\Documents and Settings\varun\Desktop\ftp.bmp");
There are also classes created specially for ftp request in .net, here is sample from MSDN
// Get the object used to communicate with the server.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.contoso.com/test.htm");
request.Method = WebRequestMethods.Ftp.UploadFile;
// This example assumes the FTP site uses anonymous logon.
request.Credentials = new NetworkCredential ("anonymous","janeDoe#contoso.com");
// Copy the contents of the file to the request stream.
StreamReader sourceStream = new StreamReader("testfile.txt");
byte [] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
sourceStream.Close();
request.ContentLength = fileContents.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Console.WriteLine("Upload File Complete, status {0}", response.StatusDescription);
response.Close();