C#连接FTP时路径出现问题的解决方法


当前第2页 返回上一页

1

ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerFilePath.Replace("\\","/")));

这样就不会跑异常,至于能否连接或者文件是否存在,请自行查看连接

https://msdn.microsoft.com/zh-cn/library/system.net.ftpstatuscode(v=vs.110).aspx

或者自行 google FtpStatusCode 即可。

那么修改后的代码为:(关于C# 连接完整的FTP 可以仔细 google 查询,网上多的是,这样就不累述了)


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

/// <summary>

 /// 测试是否可以成功连接FTP和判断文件是否存在

 /// </summary>

 /// <param name="ftpServerFilePath">FTP上文件地址</param>

 /// <param name="ftpUserId">FTP登陆用户名</param>

 /// <param name="ftpPwd">FTP登陆密码</param>

 /// <param name="errorMsg">返回错误消息</param>

 /// <returns></returns>

 private bool IsCanConnectFtp(string ftpServerFilePath, string ftpUserId, string ftpPwd, out string errorMsg)

 {

  bool flag = true;

  FtpWebResponse ftpResponse = null;

  FtpWebRequest ftpRequest = null;

  errorMsg = string.Empty;

  try

  {

   ftpRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerFilePath.Replace("\\","/")));

   ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;

   ftpRequest.Timeout = 2 * 1000;//超时时间设置为2秒。

   ftpRequest.Credentials = new NetworkCredential(ftpUserId, ftpPwd);

   ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

  }

  catch (WebException exception)

  {

   ftpResponse = (FtpWebResponse)exception.Response;

   switch (ftpResponse.StatusCode)

   {

    case FtpStatusCode.ActionNotTakenFileUnavailable:

     errorMsg = "下载的文件不存在";

     break;

    case FtpStatusCode.ActionNotTakenFileUnavailableOrBusy:

     errorMsg = "下载的文件正在使用,请稍后再试";

     break;

    default:

     errorMsg = "发生未知错误";

     break;

   }

   flag = false;

  }

  catch

  {

   errorMsg = "网络连接发生错误,请稍后再试";

   flag = true;

  }

  finally

  {

   if (ftpResponse != null)

   {

    ftpResponse.Close();

   }

  }

  return flag;

 }

总结

以上就是C#连接FTP时路径出现问题的解决方法的详细内容!

返回前面的内容

相关阅读 >>

总结一些编码和设计原则实例

c#中异步编程4async与await异步程序开发的实例分析

详细分析 .net core 构成体系(图)

有关c#工厂模式简单讲解

c#中在构造函数中访问虚成员有什么问题?

c#给图片增加文字实例代码

.net中的序列化详解

c#中ini配置文件的图文代码详解

解决visual studio 2017创建.net standard类库编译出错的问题

分享一些平时收藏和应用的开源代码

更多相关阅读请进入《csharp》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...