简体   繁体   English

在 FTP 上上传文件

[英]Upload file on FTP

I want to upload file from one server to another FTP server and following is my code to upload file but it is throwing an error as:我想将文件从一台服务器上传到另一台 FTP 服务器,以下是我上传文件的代码,但它抛出了一个错误:

The remote server returned an error: (550) File unavailable (eg, file not found, no access).远程服务器返回错误:(550) 文件不可用(例如,找不到文件,无法访问)。

This my code:这是我的代码:

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; 

Can you please tell me where i am going wrong?你能告诉我我哪里出错了吗?

Please make sure your ftp path is set as shown below.请确保您的 ftp 路径设置如下。

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

string FileName = "sample.mp4";

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

The following script work great with me for uploading files and videos to another servier via ftp.以下脚本非常适合我通过 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();

Here are sample code to upload file on FTP Server以下是在 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;
    }

You can also use the higher-level WebClient type to do FTP stuff with much cleaner code:您还可以使用更高级别的WebClient类型以更简洁的代码执行 FTP 操作:

using (WebClient client = new WebClient())
{
    client.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
    client.UploadFile("ftp://ftpserver.com/target.zip", "STOR", localFilePath);
}

In case you're still having issues here's what got me past all this.如果您仍然遇到问题,这就是让我克服这一切的原因。 I was getting the same error in-spite of the fact that I could perfectly see the file in the directory I was trying to upload - ie: I was overwriting a file.尽管我可以完美地看到我试图上传的目录中的文件,但我遇到了同样的错误 - 即:我正在覆盖一个文件。

My ftp url looked like:我的 ftp 网址如下所示:

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

So, my credentials use my tester username and PW;因此,我的凭据使用我的测试人员用户名和密码;

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

Well, my "tester" ftp account is set to " ftp://www.mywebsite.com/testingdir " but when I actually ftp [say from explorer] I just put in " ftp://www.mywebsite.com " and log in with my tester credentials and automatically get sent to "testingdir".好吧,我的“测试员”ftp 帐户设置为“ ftp://www.mywebsite.com/testingdir ”,但是当我真正进行 ftp [从资源管理器说] 时,我只是输入了“ ftp://www.mywebsite.com ”和使用我的测试人员凭据登录并自动发送到“testingdir”。

So, to make this work in C# I wound up using the url - ftp://www.mywebsite.com/myData.xml Provided my tester accounts credentials and everything worked fine.因此,为了在 C# 中完成这项工作,我最终使用了 url - ftp://www.mywebsite.com/myData.xml提供了我的测试人员帐户凭据并且一切正常。

  1. Please make sure your URL that you pass to WebRequest.Create has this format:请确保您传递给WebRequest.Create URL 具有以下格式:

     ftp://ftp.example.com/remote/path/file.zip
  2. There are easier ways to upload a file using .NET framework.使用 .NET 框架上传文件有更简单的方法。

Easiest way最简单的方法

The most trivial way to upload a file to an FTP server using .NET framework is using WebClient.UploadFile method :使用 .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");

Advanced options高级选项

If you need a greater control, that WebClient does not offer (like TLS/SSL encryption , ascii/text transfer mode, transfer resuming, etc), use FtpWebRequest , like you do.如果您需要更好的控制,该WebClient不提供(如TLS/SSL 加密、ascii/文本传输模式、传输恢复等),请使用FtpWebRequest ,就像您一样。 But you can make the code way simpler and more efficient by using Stream.CopyTo :但是您可以通过使用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);
}

For even more options, including progress monitoring and uploading whole folder, see:有关更多选项,包括进度监控和上传整个文件夹,请参阅:
Upload file to FTP using C#使用 C# 将文件上传到 FTP

Here is the Solution !!!!!!这里是解决方案!!!!!!

To Upload all the files from Local directory(ex:D:\\Documents) to FTP url (ex: ftp:\\{ip address}\\{sub dir name})将本地目录(例如:D:\\Documents)中的所有文件上传到 FTP url(例如: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";
        }

    }
    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!!");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM