保存文件到FTP服务器

保存文件到FTP服务器

问题描述:

我在asp.net和c#中创建一个文件上传器。 我只是想将上传的文件直接保存到ftp服务器。 这可能吗?如果可能的话,我该如何设置该ftp服务器认证信息。保存文件到FTP服务器

(127.0.0.1只是一个例子,我不能写我的真实ip,而且我必须使用HTTP协议来获取文件,我们的一些客户端ISP不支持ftp,这是主要问题。)

protected void submit_button_Click(object sender, EventArgs e) 
    { 
     string filename = Path.GetFileName(upload_file.FileName); 
     string fileExt = Path.GetExtension(upload_file.FileName); 

     if (fileExt == ".csv") 
     { 
      string folder = Server.MapPath("ftp://127.0.0.1/uploads/"); 
       upload_file.SaveAs(folder + "/" + filename); 
       ltr.Text = "Successful."; 
     } 
     else 
     { 
      upload_file.BorderColor = System.Drawing.Color.Red; 
      ltr.Text = "File type must be .csv."; 
     } 
    } 
+0

我不太明白你如何期望能够上传到FTP,如果你的客户端ISP的不支持FTP? – CathalMF 2013-04-30 09:43:37

它很简单。 下面的方法只是传入文件名。很明显,改变StreamReader中的目录。

编辑:对不起刚刚注意到你说你的客户端不支持FTP,所以下面将无法正常工作。

public bool ftpTransfer(string fileName) 
{ 
    try 
    { 
     string ftpAddress = "127.0.0.1"; 
     string username = "user"; 
     string password = "pass"; 

     using (StreamReader stream = new StreamReader("C:\\" + fileName)) 
     { 
      byte[] buffer = Encoding.Default.GetBytes(stream.ReadToEnd()); 

      WebRequest request = WebRequest.Create("ftp://" + ftpAddress + "/" + "myfolder" + "/" + fileName); 
      request.Method = WebRequestMethods.Ftp.UploadFile; 
      request.Credentials = new NetworkCredential(username, password); 
      Stream reqStream = request.GetRequestStream(); 
      reqStream.Write(buffer, 0, buffer.Length); 
      reqStream.Close(); 
     } 
     return true; 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex.ToString()); 
     return false; 
    } 
} 

编辑:重新编写了文件名。

+0

代码返回Not Logged In错误。我认为有任何语法记录到ftp。请问你能帮帮我吗? – user2163530 2013-04-30 09:59:34

+0

我的代码或您的代码返回“未登录错误”? – CathalMF 2013-04-30 10:17:07

string filepath = "~/txtfile/";//this is folder name wher you want to save the file 


       HttpFileCollection uploadedFiles = HttpContext.Current.Request.Files; 
       for (int i = 0; i < uploadedFiles.Count; i++) 
       { 
        HttpPostedFile userPostedFile = uploadedFiles[i]; 
        if (userPostedFile.ContentLength == 0) 
        { 
         continue; 

} 



    userPostedFile.SaveAs(Server.MapPath(filepath) + userPostedFile.filename); 
} //save file on the server