0

我有一个TXT文件,我必须将FTP它保存到FTP site.

我找不到可以帮助我编写代码的完整教程。有人可以指点我一个好的教程,或者一些代码开始吗?

4

3 回答 3

4

看起来不错。

于 2012-06-03T14:38:57.747 回答
3

正如我在评论中发布的那样,您可以看到此链接以获取有关如何将文件上传到 FTP 服务器的示例。

来自链接的代码:

using System;
using System.IO;
using System.Net;
using System.Text;

namespace Examples.System.Net
{
    public class WebRequestGetExample
    {
        public static void Main ()
        {
            // 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();
            }
        }
    }
}

要验证文件是否正确上传,您可以检查响应,它具有 StatusDescription 和 StatusCode 属性。

或者,您再次调用 FTP 服务器,在其中设置方法request.Method = WebRequestMethods.Ftp.ListDirectory;。这将返回 FTP 服务器上的文件列表。

当然这不会验证文件是否正确上传,只是有一个同名的文件。

我希望这回答了你的问题。

于 2012-06-03T14:59:12.363 回答
0

You can also try this code, applies for other file extensions too.

string ftpUrl = "ftp://server//foldername/fileName.ext";
string fileToUploaded = "c:/fileName.ext";
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl);
request.Proxy = new WebProxy(); //-----Proxy bypassing(The requested FTP command is not supported when using HTTP proxy)
request.Method = WebRequestMethods.Ftp.UploadFile;  
                request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
                using (var requestStream = request.GetRequestStream())
                {
                    using (var input = File.OpenRead(fileToBeUploaded))
                    {
                        input.CopyTo(requestStream);
                    }
                }

Try streaming the data, instead of loading it all into memory separately. Also using statement helps to dispose the resources perfectly.

于 2013-05-22T09:00:24.860 回答