Home » .Net Framework

Copy Files to FTP Server using WCF

Dear All,

I have a ftp server in my desktop computer and I want to copy files to FTP server using Windows Communication Foundation. Below is part of my code:






string OperationUploadData();


publicclassUploadServiceClass : IUploadService


publicstring OperationUploadData()




FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://pasco:22/");

request.Method = WebRequestMethods.Ftp.UploadFile;

request.Credentials = newNetworkCredential("administrator", "password");

StreamReader sourceStream = newStreamReader("test.txt");

byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());


request.ContentLength = fileContents.Length;

Stream requestStream = request.GetRequestStream();

requestStream.Write(fileContents, 0, fileContents.Length);


FtpWebResponse response = (FtpWebResponse)request.GetResponse();


return"Upload File Complete, status " + response.StatusDescription;


catch (Exception ex)


return ex.Message.ToString();





ServiceHost sh = null;

Uri tcpa = newUri("net.tcp://localhost:8000/TcpBinding");

sh = newServiceHost(typeof(UploadServiceClass), tcpa);

NetTcpBinding tcpb = newNetTcpBinding();

ServiceMetadataBehavior mBehave = newServiceMetadataBehavior();


sh.AddServiceEndpoint(typeof(IMetadataExchange), MetadataExchangeBindings.CreateMexTcpBinding(), "mex");

sh.AddServiceEndpoint(typeof(IUploadService), tcpb, tcpa);


Client Application:

TCP.UploadServiceClient client = new ClientApplication.TCP.UploadServiceClient("NetTcpBinding_IUploadService");

byte[] a = newbyte[10];

for (int i = 0; i < 10; i++)


aIdea = (byte)i;


string message = client.OperationUploadData();



Service.cs provide the contract and ServiceHost.cs provides address and bindings. When I run client application there was an error message : "The requested URI is invalid for this FTP command." I do not know how to connect FTP using WCF. I really need help as soon as possible. Thank you.


5 Answers Found


Answer 1

You shouldn't have any problems opening a FTP connection from within a WCF service.

What happens if, on the client, you actually create an instance of the service  and call the OperationUploadData directly (i.e., without WCF in the middle)?

UploadServiceClass usc = new UploadServiceClass();



Answer 2

Sorry, I just test my code  without WCF and the error message  still same. I begin think that this error  not cause by WCF. I will try to change my code first so the program can running well and try to use WCF in the middle again. I will give news if the program can running well. Thanks for your help.

Best Regards,



Answer 3

My problem has solved. I added my code  like this

FtpWebRequest request  = (FtpWebRequest)WebRequest.Create("ftp://pasco:22/" + FileName);

And now the program has running well.

Thanks again for any help that gives to me.

Best Regards,



Answer 4


  My Vb.net coding is

Dim result As FtpWebRequest = CType(FtpWebRequest.Create(URI), FtpWebRequest)

Using rs As Stream = ftp.GetRequestStream

ftp.getrequeststrem    Generate error  

Error message  is

The requested  URI is invalid  for this ftp  command.

How i solve this error , i need urgent soluction please help me




Answer 5

HI ,

I am working on exact same requirement and this is my first experience with WCF. can you please provide me some steps as to create this service. i have hard time understanding what code  goes where and how to install and test this application.. can you please take some time to gives the steps in visual studio 2008 to get this working.

thanks much for your help.




How to Get FTP Directory / File list from FTP Server - not in .html format using .net?
I am trying to develop a custom adapter that will copy two files prior to submitting the file that is picked up from the recieve location. I am thinking that I need a custom pipeline, but I am not familiar with how to do this. Has anyone done something like this? If so, could you please share some ideas or a link where I can look at an example please? Thank you.



Is there a way to copy a folder from an FTP site listening on SSH connection using DOS batch files? I know that there are several third party tools out there that accomplish this. I am NOT looking for that solution. I tried this in Powershell, but could not find a solution, and I am hoping a simple DOS batch file can handle this.


Any help would be appreciated...


Hi Guys,

      I would like to know if there's a way to create a directory on an FTP server where CWD disabled, using WebRequestMethods.Ftp.MakeDirectory without calling the CWD. As far as I know, MakeDirectory method invokes a CWD command inside the BuilDCommandList():


   if (m_PreviousServerPath != newServerPath) { 

    if (!m_IsRootPath

        && m_LoginState == FtpLoginState.LoggedIn

        && m_LoginDirectory != null)


        newServerPath = m_LoginDirectory+newServerPath;


    m_NewServerPath = newServerPath; 


    commandList.Add(new PipelineEntry(FormatFtpCommand("CWD", newServerPath), PipelineEntryFlags.UserCommand)); 



This call to CWD command throws an exemption "505 Access is denied", since FTP server does not allow it. Given this, is there a way, I can still use WebRequestMethods.Ftp.MakeDirectory? If not, what are other ways to create a folder/subdirectory on an FTP where CWD is disabled? 

Here's the WireShark logs:


220 Microsoft FTP Service

USER <user>

331 Password required for <user>.

PASS <password>

230-Directory has 2,330,700,443,648 bytes of disk space available.

230 User logged in.

OPTS utf8 on

200 OPTS UTF8 command successful - UTF8 encoding now ON.


257 "/" is current directory.

CWD /<subdir>/

550 Access is denied. 



Your response is really appreciated. :)




Using window file share(ftp://sharepointserver/drop) i want to send the report from the report server machine to the  sharepoint servers ftp drop folder and then by mapping the sharepoint doc lib to the ftp drop folder, upload the reports into sharepoint doc library???

Is this possible??

Get Image From FTP Server in the report and FTP server Has UserName & Password


We are running:

Microsoft SQL Server 2005 Standard - 9.00.4294.00 (X64)
Microsoft Windows Server 2003 R2 Enterprise x64

We have gigabit interface.

Today we copied a file (using robocopy) from our databaseserver to another server (backup-server). The copy was started from the backup-server and source were specified using UNC.

The copy were using about 20% of the bandwith (about 200Mbit).

During the copy, sql-server reported several errors, for example:

AppDomain 15 (mp.dbo[runtime].14) is marked for unload due to memory pressure. The client was unable to reuse a session with SPID 75, which had been reset for connection pooling. This error may have been caused by an earlier operation failing. Check the error logs for failed operations immediately before this error message. ***Stack Dump being sent to [PATH\SQLDump0005.txt Resource Monitor (0x1384) Worker 0x000000008000C1C0 appears to be non-yielding on Node 0. Memory freed: 0 KB. Approx CPU Used: kernel 15 ms, user 218 ms, Interval: 428541.

So to me it appears that sql-server crashed during a file copy.

We have 27 GB ram. With 24.5 GB dedicated to SQL-Server.
The files we copied were quite large, some over 50GB.

I found a similar issue about this: http://support.microsoft.com/kb/920739/

Do you think the issue above could be the cause of the sql-server crash?



I am using File.Copy to copy three jpeg file on Window 7.

Sometime what happens that the size of image increases considerably from 4 MB to 17 MB. Upon investigation i come to know that  certain propery of image have changes which increses its size. 



horizontal resolution : 72 dpi , 

vertical resolution : 72 dpi 

Bit depth : 24




Horizontal resolution : 346 dpi

Vertical resolution : 346 dpi

Bit Depth : 32


I don't know what is causing this. Plz help me. Thanks in advance.


Hello everybody!

What is the most preferable way to check whether file exists on ftp server?

It seems to me that I should use either  WebRequestMethods.Ftp.ListDirectory or WebRequestMethods.Ftp.GetFileSize method and then parse response, but what is the most effective and cheapest one? Or maybe there is another solution to this problem...

Thanks in advance.



Hi I am encountering weird situation I am in exact same situation below link  In below link there is a suggestion to overcome this situation but it doesn't work at all.  Please take a look at link below for detail I am not good at english


I am using sql server 2005 sp2.  I think there is some connection time limit or whatever. When i tried to download 100mb file from local ftp server, The file was downloaded successfully because it take a short time to download file. but When i tried to download 100mb file from remote server It failed since remote server and sql server is connected with slow internet link. It takes 6 minutes to get file from remote server and 1 minutes to get file from local ftp server.  If i make standalone application from exact same codes, It works well even if i connected remote server. It happens only when it goes to SQL CLR environment. 

Any advice will be appreciated in advance





Hi there,

I've searched a few topics regarding to the script sample of rename files in SSIS. However, it seems to be too complicate for me. I just wanna rename files' extension name on FTP folder, for example, rename all unprocessed files from *.txt to *.toproc, and then download to be processed.

Can anyone give me a simple sample code for it.

Thanks in advance!


hi guys,

i want to upload file to ftp server using file upload tool from toolbox.how can i do?


Hi I am getting 550 File unavliable error why



void Download(string filePath, string fileName)



FtpWebRequest reqFTP;





//filePath: The full path where the file is to be created.


//fileName: Name of the file to be createdNeed not name on


// the FTP server. name name()


FileStream outputStream = newFileStream(filePath + "\\" +



reqFTP = (


reqFTP.Method =


reqFTP.UseBinary =


reqFTP.EnableSsl =


reqFTP.Credentials =

newNetworkCredential("ashok", "*****");


FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();



Stream ftpStream = response.GetResponseStream();  -- here getting error


long cl = response.ContentLength;


int bufferSize = 2048;


int readCount;


byte[] buffer = newbyte[bufferSize];

readCount = ftpStream.Read(buffer, 0, bufferSize);


while (readCount > 0)


outputStream.Write(buffer, 0, readCount);

readCount = ftpStream.Read(buffer, 0, bufferSize);







catch (Exception ex)






I'd like to use System.Net to connect to FTP Server and it does, but now i want to have a form to display the contents of the FTP Server (example: It shows the files and folders and allows the viewing of another folder, like an ftp client but not used for that)

Issue regarding downloading same file again and again. Let me be clear, I am using SSIS to poll FTP Server on regular intervals to download different files to my local directory. Once the file is downloaded I need to load the file name into table and validate that particular file name against FTP Server next time when I am polling, so that I don't download same file again. 

                            Question here is how could I implement this either using SSIS or VB Script ???



  Is it possible to write a custom timer job, which executes a powershell command at specified interval 

Powershell command copies files from ftp server to sharepoint site

 Or Is there any other way to upload files from FTP server to sharepoint site.



Can you help me? This function worked well a few hours ago and now i only get".." returned. I have multiple files on the ftp server.
Thank you for your time!
Function FisierePeFTP() AsString()

Dim lines AsNew ArrayList

Dim sr As System.IO.StreamReader

Dim clsRequest As System.Net.FtpWebRequest

clsRequest = DirectCast(System.Net.FtpWebRequest.Create("someftp"), System.Net.FtpWebRequest)

clsRequest.Method = System.Net.WebRequestMethods.Ftp.ListDirectory

clsRequest.Credentials = New System.Net.NetworkCredential("user", "pass")

' read the file's lines into an ArrayListTry

sr = New System.IO.StreamReader(clsRequest.GetResponse.GetResponseStream)

DoWhile sr.Peek() >= 0



LoopFinallyIfNot sr IsNothingThen sr.Close()

EndTry' convert from ArrayList to a String arrayReturnCType(lines.ToArray(GetType(String)), String())




Can we upload and download files from remote servers without using FTP?

If yes can you please tell me how can we do that?

Thanks in advance,

Vikas Jaigude. 



How to lock a file when we are writing to FTP Location?

Scenario :

I have Folder which act as a receive location and send location for Biztalk.

When i am sending a file to FTP location folder,

other biztalk process will be monitoring that process.Once the file get generated in this folder it will pick the file.

So if 100kb file is writing to FTP location, without completing this file other BT process will pick some part of the file,

How can i lock the FTP location file using Biztalk server.


Hi Guys,

I'm trying to push the contents of a folder(files & sub-directories) to an ftp server. Can I get a nice sample?



<< Previous      Next >>

Microsoft   |   Windows   |   Visual Studio   |   Sharepoint   |   Azure