c# ftp上传方式把文件上传到指定服务器!

c# ftp上传方式把文件上传到指定服务器!

第1个回答  推荐于2017-11-29
/// <summary>
/// 上传文件到FTP服务器
/// </summary>
/// <param name="ftpServerIp">FTP访问地址</param>
/// <param name="userName">用户名</param>
/// <param name="userPass">密码</param>
/// <param name="strPath">地址</param>
/// <returns></returns>
public static bool UpLoadFileFtp(string ftpServerIp, string userName, string userPass, string filePath, string strPath)
{
bool res =false;
string ftpUrl = CommConst.ftpName;
string uri = string.Empty;
if (!string.IsNullOrEmpty(strPath))
{
FileInfo file = new FileInfo(strPath);
if (!file.Exists)
{
res = false;
}
else
{

uri = ftpUrl + ftpServerIp + file.Name;
FtpWebRequest reqFtp=(FtpWebRequest)WebRequest.Create(new Uri(uri));

DealFile(ftpServerIp, userName, userPass);//查看服务器上是否存在指定文件夹

reqFtp.Credentials = new NetworkCredential(userName, userPass);
reqFtp.KeepAlive = false;
reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
reqFtp.UseBinary = true;
reqFtp.ContentLength = file.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = file.OpenRead();
try
{
Stream strm = reqFtp.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}

strm.Close();
fs.Close();
res = true;
}
catch (Exception ex)
{
Console.Write(ex.Message);
return false;
}
}
}
return res;
}
/// <summary>
/// 处理上传文件的路径,如果不存在,新建
/// </summary>
public static void DealFile(string ftpServerIp, string userName, string userPass)
{
string[] Paths = ftpServerIp.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string realftpURL = CommConst.ftpName + Paths[0];//需要查询的ftp路径
if (Paths!=null && Paths.Length >= 2)
{
string fileName = "";
for (int i = 0; i < Paths.Length - 1; i++)
{
if (i != 0)
{
fileName = Paths[i] + CommConst.bevelSign + Paths[i + 1];
}
else
{
fileName = Paths[i + 1];
}

if (!fileIsexit(realftpURL, userName, userPass, fileName))//如果文件夹不存在
{
// realftpURL += CommConst.bevelSign + Paths[i + 1];
CreateFile(realftpURL, userName, userPass,Paths[i+1]);
}
realftpURL += CommConst.bevelSign + Paths[i + 1];
}
}

}本回答被提问者采纳
第2个回答  2014-01-15
ftp有链接服务器的设置、设置好服务器直接传上就好啦追问

ftp是一个空间 服务器也是一个空间 他俩有什么关联呢?

相似回答