在FTP上传文件

时间:2012-04-14 06:49:47

标签: c# asp.net .net ftp ftpwebrequest

我想将文件从一台服务器上传到另一台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; 

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

7 个答案:

答案 0 :(得分:37)

请确保您的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();

答案 1 :(得分:13)

以下是在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;
    }

答案 2 :(得分:13)

您还可以使用更高级别的WebClient类型来使用更清晰的代码来执行FTP操作:

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

答案 3 :(得分:2)

如果你在这里仍有问题,那么是什么让我过去这一切。 我得到了同样的错误,尽管我可以在我试图上传的目录中完美地看到该文件 - 即:我正在覆盖文件。

我的ftp网址看起来像:

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

所以,我的凭据使用我的测试人员用户名和PW;

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

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

所以,为了在C#中完成这项工作,我使用了网址 - ftp://www.mywebsite.com/myData.xml 如果我的测试人员帐户凭据,一切正常。

答案 4 :(得分:1)

  1. 请确保您传递给WebRequest.Create的URL具有以下格式:

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

最简单的方法

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

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

有关更多选项(包括进度监视和上传整个文件夹),请参见:
Upload file to FTP using C#

答案 5 :(得分:0)

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

要将所有文件从本地目录(例如:D:\ Documents)上载到FTP网址(例如:ftp:\ {ip地址} \ {sub dir名称})

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

    }

答案 6 :(得分:-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!!");
}