使用C#将文件从ftp复制到远程桌面

问题描述:

你好,

我必须将文件从ftp复制到远程台式计算机.

Hello,

i have to copy files from ftp to remote desktop computer.

try
{
    File.Copy("ftp://IP Address:Port/My Folder/MyFile.dll", @"Remote IP Address\My Location");
}
catch(Exception ex)
{
    Console.Write(ex.Message);
}



但是,我做不到.我认为可能的原因可能是:
(1)ftp和远程桌面需要密码(凭据).
(2)我正在尝试将文件复制到未共享的文件夹中.
(3)还有其他问题.....


if(1),那么如何处理我代码中的凭据?
if(2),那么如何将文件复制到不共享的文件夹?
if(3),请告诉我实际原因以及如何处理?

谢谢,



But, i could not do this. I think the possible reasons might be:
(1)the ftp and remote desktop requires password (credentials).
(2)i am trying to copy file to a folder who is not shared.
(3)Any other issue........


if(1), then how can handle credentials in my code?
if(2), then how can copy files to a folder who is not shared?
if(3), tell me the actual reason and how to handle it?

thanks,

在MSDN上查看此文章
如何:使用FTP上传文件 [
Take a look at this article on MSDN
How to: Upload Files with FTP[^].

It outlines how to use credentials and such with a very nice clean code sample.


文件复制不适用于FTP.我在过去的回答中提供了完整的解决方案,请参阅: FTP:下载文件 [ ^ ].

File copy does not work with FTP. I provided a complete solution in my past answer, please see: FTP: Download Files[^].


您必须使用FtpWebRequest& FtpWebResponse,然后您必须获得响应.
You have to use FtpWebRequest & FtpWebResponse and after that you have to get response.
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://path/test.htm");
            request.Method = WebRequestMethods.Ftp.UploadFile;
            // This example assumes the FTP site uses anonymous logon.
            request.Credentials = new NetworkCredential ("anonymous","abc@xyz.com");            
            
            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();
    
            response.Close();