C# Ftp文件处理

时间:2022-07-17 03:44:12

1.创建文件夹

/// <summary>
/// ftp创建文件夹(只能创建单层目录)
/// </summary>
/// <param name="Uri">IP服务地址</param>
/// <param name="UserName">登陆账号</param>
/// <param name="UserPass">密码</param>
public static bool CreateDirectory(string Uri, string UserName, string UserPass)
{
    try
    {
        FtpWebRequest FTP = (FtpWebRequest)FtpWebRequest.Create(Uri);
        FTP.Credentials = new NetworkCredential(UserName, UserPass);
        FTP.Proxy = null;
        FTP.KeepAlive = false;
        FTP.Method = WebRequestMethods.Ftp.MakeDirectory;
        FTP.UseBinary = true;
        FtpWebResponse response = FTP.GetResponse() as FtpWebResponse;
        response.Close();
        return true;
    }
    catch
    {
        return false;
    }
}

注意 这个方法只能创建一层目录,如果要创建深层目录,只能迭代。

这个方法也可以用来判断某个目录是否存在(网上找了几个判断目录存在与否的方法,都有Bug,没解决掉)

如果文件夹已存在或者指定目录的父文件夹不存在,则抛出【远程服务器返回错误: (550) 文件不可用(例如,未找到文件,无法访问文件)。】

 


Ftp 读取文件到字符串中(下载)

public String readerFtpFile(String ftp, String username, String password, String filename)
{
    StringBuilder result = new StringBuilder(); 
    FtpWebRequest reqFTP;
    try
    {
        String ftpserver = ftp + filename;
        reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpserver));
        reqFTP.UsePassive = false;
        reqFTP.UseBinary = true;
        reqFTP.Credentials = new NetworkCredential(username, password);
        //reqFTP.Method?=?WebRequestMethods.Ftp.ListDirectory;
        reqFTP.Method?=?WebRequestMethods.Ftp.DownloadFile;
        FtpWebResponse fwResponse = (FtpWebResponse)reqFTP.GetResponse();
        StreamReader reader = new StreamReader(fwResponse.GetResponseStream(),Encoding.UTF8);
        
        string line = reader.ReadLine();
        while (line != null)
        {
            result.AppendLine(line);
            line = reader.ReadLine();
        }
        result.Remove(result.ToString().LastIndexOf('\n'), 1);
        reader.Close();
        fwResponse.Close();
        return result.ToString();
    }
    catch (Exception ex)
    {
        return result.ToString();
    }
}

 


Ftp 文件上传:

string url = string.Format("ftp://{0}/{1}/{2}", FtpIP, UploadPath,fileName);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url);
request.Credentials = new NetworkCredential(FtpUserName, FtpPwd);
request.Proxy = null;
request.Method = WebRequestMethods.Ftp.UploadFile;
Stream stream = request.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
stream.Close();

注意这一句[request.Proxy = null;]因为公司都是代理上网,所以如果不加这句话,就会报错误【使用 HTTP 代理时不支持请求的 FTP 命令。】

还有一点就是 ftp地址必须使用内网IP,而不是外网IP,否则会出现错误【无法解析此远程名称】