24

我想将文件从一台服务器上传到另一台 FTP 服务器,以下是我上传文件的代码,但它引发错误:

远程服务器返回错误:(550) 文件不可用(例如,找不到文件,无法访问)。

这是我的代码:

string CompleteDPath = "ftp URL";
string UName = "UserName";
string PWD = "Password";
WebRequest reqObj = WebRequest.Create(CompleteDPath + FileName);
reqObj.Method = WebRequestMethods.Ftp.UploadFile;
reqObj.Credentials = new NetworkCredential(UName, PWD);
FileStream streamObj = System.IO.File.OpenRead(Server.MapPath(FileName));
byte[] buffer = new byte[streamObj.Length + 1];
streamObj.Read(buffer, 0, buffer.Length);
streamObj.Close();
streamObj = null;
reqObj.GetRequestStream().Write(buffer, 0, buffer.Length);
reqObj = null; 

你能告诉我哪里出错了吗?

4

7 回答 7

39

请确保您的 ftp 路径设置如下所示。

string CompleteDPath = "ftp://www.example.com/wwwroot/videos/";

string FileName = "sample.mp4";

WebRequest reqObj = WebRequest.Create(CompleteDPath + FileName);

以下脚本非常适合我通过 ftp 将文件和视频上传到另一个服务器。

FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(ftpurl + "" + username + "_" + filename);
ftpClient.Credentials = new System.Net.NetworkCredential(ftpusername, ftppassword);
ftpClient.Method = System.Net.WebRequestMethods.Ftp.UploadFile;
ftpClient.UseBinary = true;
ftpClient.KeepAlive = true;
System.IO.FileInfo fi = new System.IO.FileInfo(fileurl);
ftpClient.ContentLength = fi.Length;
byte[] buffer = new byte[4097];
int bytes = 0;
int total_bytes = (int)fi.Length;
System.IO.FileStream fs = fi.OpenRead();
System.IO.Stream rs = ftpClient.GetRequestStream();
while (total_bytes > 0)
{
   bytes = fs.Read(buffer, 0, buffer.Length);
   rs.Write(buffer, 0, bytes);
   total_bytes = total_bytes - bytes;
}
//fs.Flush();
fs.Close();
rs.Close();
FtpWebResponse uploadResponse = (FtpWebResponse)ftpClient.GetResponse();
value = uploadResponse.StatusDescription;
uploadResponse.Close();
于 2012-04-14T07:54:39.690 回答
14

这是在 FTP 服务器上上传文件的示例代码

    string filename = Server.MapPath("file1.txt");
    string ftpServerIP = "ftp.demo.com/";
    string ftpUserName = "dummy";
    string ftpPassword = "dummy";

    FileInfo objFile = new FileInfo(filename);
    FtpWebRequest objFTPRequest;

    // Create FtpWebRequest object 
    objFTPRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + objFile.Name));

    // Set Credintials
    objFTPRequest.Credentials = new NetworkCredential(ftpUserName, ftpPassword);

    // By default KeepAlive is true, where the control connection is 
    // not closed after a command is executed.
    objFTPRequest.KeepAlive = false;

    // Set the data transfer type.
    objFTPRequest.UseBinary = true;

    // Set content length
    objFTPRequest.ContentLength = objFile.Length;

    // Set request method
    objFTPRequest.Method = WebRequestMethods.Ftp.UploadFile;

    // Set buffer size
    int intBufferLength = 16 * 1024;
    byte[] objBuffer = new byte[intBufferLength];

    // Opens a file to read
    FileStream objFileStream = objFile.OpenRead();

    try
    {
        // Get Stream of the file
        Stream objStream = objFTPRequest.GetRequestStream();

        int len = 0;

        while ((len = objFileStream.Read(objBuffer, 0, intBufferLength)) != 0)
        {
            // Write file Content 
            objStream.Write(objBuffer, 0, len);

        }

        objStream.Close();
        objFileStream.Close();
    }
    catch (Exception ex)
    {
        throw ex;
    }
于 2012-05-15T13:44:22.880 回答
14

您还可以使用更高级别的WebClient类型来使用更简洁的代码执行 FTP 工作:

using (WebClient client = new WebClient())
{
    client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
    client.UploadFile("ftp://ftpserver.com/target.zip", "STOR", localFilePath);
}
于 2015-09-23T13:01:47.990 回答
2

如果您仍然遇到问题,这就是让我克服这一切的原因。尽管我可以完美地看到我尝试上传的目录中的文件,但我遇到了同样的错误 - 即:我正在覆盖一个文件。

我的 ftp 网址看起来像:

// ftp://www.mywebsite.com/testingdir/myData.xml
FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://www.mywebsite.com/testingdir/myData.xml"

因此,我的凭据使用我的测试人员用户名和密码;

request.Credentials = new NetworkCredential ("tester", "testerpw");

好吧,我的“测试人员”ftp 帐户设置为“ ftp://www.mywebsite.com/testingdir ”,但是当我实际 ftp [从资源管理器中说]时,我只是输入了“ ftp://www.mywebsite.com ”并且使用我的测试人员凭据登录并自动发送到“testingdir”。

因此,为了在 C# 中完成这项工作,我最终使用了 url - ftp://www.mywebsite.com/myData.xml 提供了我的测试人员帐户凭据,一切正常。

于 2013-01-25T22:02:26.830 回答
1
  1. 请确保您传递给的 URLWebRequest.Create具有以下格式:

     ftp://ftp.example.com/remote/path/file.zip
    
  2. 使用 .NET 框架上传文件有更简单的方法。

最简单的方法

使用 .NET 框架将文件上传到 FTP 服务器的最简单的方法是使用WebClient.UploadFile方法

WebClient client = new WebClient();
client.Credentials = new NetworkCredential("username", "password");
client.UploadFile(
    "ftp://ftp.example.com/remote/path/file.zip", @"C:\local\path\file.zip");

高级选项

如果您需要更大的控制,WebClient但不提供(如TLS/SSL 加密、ascii/文本传输模式、传输恢复等),FtpWebRequest请像您一样使用。但是您可以使用以下方法使代码更简单、更高效Stream.CopyTo

FtpWebRequest request =
    (FtpWebRequest)WebRequest.Create("ftp://ftp.example.com/remote/path/file.zip");
request.Credentials = new NetworkCredential("username", "password");
request.Method = WebRequestMethods.Ftp.UploadFile;  

using (Stream fileStream = File.OpenRead(@"C:\local\path\file.zip"))
using (Stream ftpStream = request.GetRequestStream())
{
    fileStream.CopyTo(ftpStream);
}

有关更多选项,包括进度监控和上传整个文件夹,请参阅:
使用 C# 将文件上传到 FTP

于 2018-12-15T11:37:13.410 回答
0

这是解决方案!!!!!!!

将本地目录(ex:D:\Documents) 中的所有文件上传到 FTP url (ex: ftp:\{ip address}\{sub dir name})

public string UploadFile(string FileFromPath, string ToFTPURL, string SubDirectoryName, string FTPLoginID, string
FTPPassword)
    {
        try
        {
            string FtpUrl = string.Empty;
            FtpUrl = ToFTPURL + "/" + SubDirectoryName;    //Complete FTP Url path

            string[] files = Directory.GetFiles(FileFromPath, "*.*");    //To get each file name from FileFromPath

            foreach (string file in files)
            {
                FtpWebRequest request = (FtpWebRequest)FtpWebRequest.Create(FtpUrl + "/" + Path.GetFileName(file));
                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.Credentials = new NetworkCredential(FTPLoginID, FTPPassword);
                request.UsePassive = true;
                request.UseBinary = true;
                request.KeepAlive = false;

                FileStream stream = File.OpenRead(FileFromPath + "\\" + Path.GetFileName(file));
                byte[] buffer = new byte[stream.Length];


                stream.Read(buffer, 0, buffer.Length);
                stream.Close();

                Stream reqStream = request.GetRequestStream();
                reqStream.Write(buffer, 0, buffer.Length);
                reqStream.Close();
            }
            return "Success";
        }
        catch(Exception ex)
        {
            return "ex";
        }

    }
于 2018-12-14T10:47:44.197 回答
-1
    public void UploadImageToftp()

        {

     string server = "ftp://111.61.28.128/Example/"; //server path
     string name = @"E:\Apache\htdocs\visa\image.png"; //image path
      string Imagename= Path.GetFileName(name);

    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri(string.Format("{0}{1}", server, Imagename)));
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential("username", "password");
    Stream ftpStream = request.GetRequestStream();
    FileStream fs = File.OpenRead(name);
    byte[] buffer = new byte[1024];
    int byteRead = 0;
    do
    {
        byteRead = fs.Read(buffer, 0, 1024);
        ftpStream.Write(buffer, 0, byteRead);
    }
    while (byteRead != 0);
    fs.Close();
    ftpStream.Close();
    MessageBox.Show("Image Upload successfully!!");
}
于 2017-05-25T05:48:47.110 回答