【问题标题】:Uploading into folder in FTP?上传到FTP中的文件夹?
【发布时间】:2013-12-31 22:15:28
【问题描述】:

我正在使用以下代码来学习如何使用 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();
            }
        }
    }
}

【问题讨论】:

    标签: c# ftp


    【解决方案1】:

    该文件夹是您在创建 request 时设置的 URL 的一部分:"ftp://www.contoso.com/test.htm"。如果您使用"ftp://www.contoso.com/wibble/test.htm",则文件将上传到名为wibble 的文件夹中。

    如果wibble 文件夹尚不存在,您可能需要先使用带有Method = WebRequestMethods.Ftp.MakeDirectory 的请求来创建它。

    【讨论】:

    • 我使用的是 ftp.myserver.com/myfolder。我收到错误 - System.UriFormatException:无效的 URI:无法确定 URI 的格式。我该如何解决这个问题?
    • 前面有没有ftp://?
    • 我把它做成了 ftp : // myserver 。 com / myfolder 并收到错误 - System.Net.WebException: Unable to connect to the remote server
    • 我特意把这些空格都放在ftp地址里,这样SO就不会把它转换成链接了。
    • ftp 字符串有两个用途,因此可能需要两次:首先作为开头"ftp://" 中的“协议说明符”,其次它可能是远程服务器主机名的一部分。您之前的示例将其作为主机名的一部分,但您的最新示例没有。你应该使用ftp://ftp.myserver.com/myfolder 吗?
    猜你喜欢
    • 2012-04-21
    • 2012-07-06
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    • 2012-02-22
    • 1970-01-01
    • 2016-06-22
    相关资源
    最近更新 更多