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#中委托和匿名委托的具体介绍

c#中如何使用sendmessage?

c#开发中遇到的问题分享

mes溯源方案追溯系统开发

c# invoke 和 begininvoke之间的区别详解

c#如何通过对象属性名修改值的实例

.net中core使用socket与树莓派进行通信的实例分析(图文)

c#中foreach与yield的实例详解

asp.net开发实用工具

关于.net 3.5中的委托实例

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




打赏

取消

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

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

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

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

评论

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