c# - 我如何使用ftp服务器上传文件?

标签 c# asp.net-mvc-3

我的网站有一个主机,这个主机没有足够的空间来存放我的文件,我让另一个主机把我的文件保存在这个主机上我有 ftp 地址和用户名并通过

我找到这段代码

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

但是

我如何使用 ftp 将我的文件上传到另一个主机并获取保存文件的 url 位置?

最佳答案

你选择你上传到ftp的路径附加目录到FTP地址:

string CompleteDPath = "ftp://yourFtpHost/folder1/folder2/";

string FileName = "yourfile.txt";

这里有一个我曾经找到的工作示例:

WebRequest reqObj = WebRequest.Create(CompleteDPath + FileName);
The following script work great with me for uploading files and videos to another servier via 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();

摘自这里:

Upload file on ftp

关于c# - 我如何使用ftp服务器上传文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17463859/

相关文章:

c# - 将价格除以 3

c# - 使用 HtmlHelper 创建 jQuery UI 对话框

asp.net-mvc - 模型和 View 模型之间的区别

c# - 使用反射双向自动映射所有域实体以查看 MVC3 中的模型

c# - WinRT C++(Win10)、opencv HSV色彩空间、图像显示、神器

c# - Twitter OAuth Flow - 对 oob/3-legged auth 和一般流程感到困惑,不需要 PIN?

c# - C#代码错误名称“i”不存在

javascript - 在浏览器中按下“返回”时删除 TempData 值 asp.net mvc 3

c# - 类似但不完全相同的元素的 MVC 部分 View

c# - Mysql 连接不适用于 "using"