FtpWebRequest
实现文本传输协议。
public sealed class FtpWebRequest : WebRequest
实现从Ftp服务器上下载文件:
FtpWebRequest req = (FtpWebRequest)WebRequest.Create("ftp://ip/2014-7-12-21-8-29-725.wav");
req.Method = WebRequestMethods.Ftp.DownloadFile;
req.UseBinary = true;
req.UsePassive = true;
req.Credentials = new NetworkCredential("***name", "***pwsd");
try
{
using (FtpWebResponse res = (FtpWebResponse)req.GetResponse())
{
string localfile = Path.Combine("D:TTSVoices", "a.wav");
FileStream fs = new FileStream(localfile, FileMode.Create, FileAccess.Write);
int buffer = 1024; //1K缓冲
byte[] b = new byte[buffer];
int i = 0;
Stream stream = res.GetResponseStream();
while ((i = stream.Read(b, 0, buffer)) > 0)
{
fs.Write(b, 0, i);
}
}
}
catch (Exception ex)
{
}
finally
{
}
实现往Ftp服务器上传输文件:
FileInfo file = new FileInfo(Server.MapPath(strPath));
if (!File.Exists(Server.MapPath(strPath)))
throw new Exception("未找到相应文件地址");
FileStream fs1 = file.Open(FileMode.Open);
StreamReader sread = new StreamReader(fs1);
string NewFileName = Guid.NewGuid().ToString("N") + Path.GetExtension(file.Name);
string UriStr = Path.Combine("ftp://ip/", NewFileName);
FtpWebRequest reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(UriStr));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential("xnyq", "faxftp_xnyq");
reqFTP.KeepAlive = false;
reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
reqFTP.ContentLength = file.Length;
byte[] buff = new byte[file.Length];
int buffLength = 2048, contentLen = 0;//缓存大小
Stream fs = sread.BaseStream;
try
{
Stream strm = reqFTP.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
// 把内容从file stream 写入upload stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
}
catch (Exception error) { throw error; }
finally { fs.Close(); sread.Close(); }
备注:
创建FTP站点完成后,测试连接,直接输入ftp务器ip地址:ftp端口。弹出输入用户名和密码的对话框表示配置成功,正确的输入用户名和密码后,即可对FTP文件进行相应权限的操作。
如果不能操作或连接,要对FTP服务器对应的文件设置开放权限。