Reputation: 41
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.
Upvotes: 2
Views: 4799
Reputation: 50752
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","[email protected]");
// 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();
Upvotes: 1
Reputation: 263167
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.
Upvotes: 1