C#FTP和Windows服务 [英] C# FTP and windows services

查看:97
本文介绍了C#FTP和Windows服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好



我想在C#上做服务,在FTP上用我的服务下载文件



我的代码:

  public   string  [] directoryListSimple(ITEM Line, string 目录)
{
try
{
/ * 创建FTP请求* /
ftpRequest = (FtpWebRequest)WebRequest.Create(host + / +目录);
/ * 使用提供的用户名和密码登录FTP服务器* /
ftpRequest.Credentials = new NetworkCredential(user,pass);
ftpRequest.UseBinary = true ;
ftpRequest.UsePassive = false ;
ftpRequest.KeepAlive = true ;
/ * 指定FTP请求的类型* /
ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
/ * 建立与FTP服务器的返回通信* /
ftpResponse =( FtpWebResponse)ftpRequest.GetResponse();
/ * 建立与FTP服务器的返回通信* /
ftpStream = ftpResponse .GetResponseStream();
/ * 获取FTP服务器的响应流* /
StreamReader ftpReader = < span class =code-keyword> new StreamReader(ftpStream);
/ * 存储原始响应* /
string directoryRaw = null ;
/ * 读取响应的每一行并为每条线附加管道以便于解析* /
尝试
{
while (ftpReader.Peek( )!= -1)
{
directoryRaw + = ftpReader.ReadLine()+ | ;
}
}
catch (例外情况)
{
Line.ERROR = TRUE;
CL_TRAVAIL.Instance.LOG( ERROR 2 = + ex.ToString()) ;
}
ftpReader.Close();
ftpStream.Close();
ftpResponse.Close();
ftpRequest = null ;

/ * 资源清理* /
/ * 将目录列表作为字符串返回,通过使用您附加的分隔符解析'directoryRaw'(我在本例中使用|)* /
尝试
{
string [] directoryList = directoryRaw.Split( | .ToCharArray());
Line.ERROR = FASLE;
return directoryList;
}
catch (例外情况)
{
Line.ERROR = TRUE;
CL_TRAVAIL.Instance.LOG( ERROR 2 = + ex.ToString()) ;
}
/ * 如果发生异常,则返回空字符串数组* /
return new string [ ] { };
}
catch (例外情况)
{
Line.ERROR = TRUE;
CL_TRAVAIL.Instance.LOG( ERROR 3 = + ex.ToString()) ;
return new string [ ] { };
}

}





我的错误在这一行:ftpResponse =(FtpWebResponse)ftpRequest .GetResponse();



< pre> 
10:40:29 - ERROR 3 = System.Net.WebException:La connexion sous-jacenteaétéfermée:Une erreur inattendue s'est produite lors delaréception。 $ b $bàSystem.Net.FtpWebRequest.CheckError()$ b $bàSystem.Net.FtpWebRequest.SyncRequestCallback(Object obj)$ b $bàSystem.Net.CommandStream.Abort(Exception e)
àSystem.Net.CommandStream.CheckContinuePipeline()$ b $bàSystem.Net.FtpDataStream.System.Net.ICloseEx.CloseEx(CloseExState closeState)$ b $bàSystem.Net.FtpDataStream.Dispose(布尔处理)$ b $bàSystem.IO.Stream.Close()$ b $bàSystem.IO.StreamReader.Dispose(布尔处理)$ b $bàWindowsService.FTP.directoryListSimple(ITEM Line,String directory)







我的尝试:



您好



我在Windows窗体应用程序中使用我的代码并且它可以工作,但是当我在我的服务应用程序中使用它时它不起作用。



有人有个主意



谢谢

解决方案

< blockquote>尝试将 ftpwebrequest.timeout 值设置为-1(无限制) )。 MS文档说它设置为,但它实际上设置为100000(100秒)。


我使用它并且它的工作我不知道为什么???



 public List< string> directoryListSimple(ITEM Line,string directory)
{

List< string> directoryList = new List< string>();

FtpWebRequest request =(FtpWebRequest)WebRequest.Create(host +/+ directory);
request.Method = WebRequestMethods.Ftp.ListDirectory;

//此示例假定FTP站点使用匿名登录。
request.Credentials = new NetworkCredential(user,pass);
FtpWebResponse response =(FtpWebResponse)request.GetResponse();
流responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
//Console.WriteLine(reader.ReadToEnd());

while(!reader.EndOfStream)
{
directoryList.Add(reader.ReadLine());
}
Console.WriteLine(目录列表完成,状态{0},response.StatusDescription);

reader.Close();
responseStream.Close();
response.Close();
request = null;
reader = null;
responseStream = null;
response = null;

返回directoryList;
}


与我合作的解决方案



尝试
{

FtpWebRequest ftpReq =(FtpWebRequest)WebRequest.Create(host +/+ remoteFile);
ftpReq.UseBinary = true;
ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
ftpReq.Credentials = new NetworkCredential(user,pass);

byte [] b = File.ReadAllBytes(localFile);

ftpReq.ContentLength = b.Length;
using(Stream s = ftpReq.GetRequestStream())
{
s.Write(b,0,b.Length);
}

FtpWebResponse ftpResp =(FtpWebResponse)ftpReq.GetResponse();

if(ftpResp!= null)
{
OUTILS.LOG(MSG FTP =+ ftpResp.StatusDescription.ToString());
}
}
catch(例外e)
{
OUTILS.LOG(ERROR START);
OUTILS.LOG(MSG =+ e.ToString());
OUTILS.LOG(ERROR END);
}


Hello

I want to do a service in C# and my service download file on a FTP

My code :

public string[] directoryListSimple(ITEM Line, string directory)
        {
            try
            {
                /* Create an FTP Request */
                ftpRequest = (FtpWebRequest)WebRequest.Create(host + "/" + directory);
                /* Log in to the FTP Server with the User Name and Password Provided */
                ftpRequest.Credentials = new NetworkCredential(user, pass);
                ftpRequest.UseBinary = true;
                ftpRequest.UsePassive = false;
                ftpRequest.KeepAlive = true;
                /* Specify the Type of FTP Request */
                ftpRequest.Method = WebRequestMethods.Ftp.ListDirectory;
                /* Establish Return Communication with the FTP Server */
                ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();
                /* Establish Return Communication with the FTP Server */
                ftpStream = ftpResponse.GetResponseStream();
                /* Get the FTP Server's Response Stream */
                StreamReader ftpReader = new StreamReader(ftpStream);
                /* Store the Raw Response */
                string directoryRaw = null;
                /* Read Each Line of the Response and Append a Pipe to Each Line for Easy Parsing */
                try
                {
                    while (ftpReader.Peek() != -1)
                    {
                        directoryRaw += ftpReader.ReadLine() + "|";
                    }
                }
                catch (Exception ex)
                {
                    Line.ERROR = "TRUE";
                    CL_TRAVAIL.Instance.LOG("ERROR 2 = " + ex.ToString());
                }
                ftpReader.Close();
                ftpStream.Close();
                ftpResponse.Close();
                ftpRequest = null;

                /* Resource Cleanup */
                /* Return the Directory Listing as a string Array by Parsing 'directoryRaw' with the Delimiter you Append (I use | in This Example) */
                try
                {
                    string[] directoryList = directoryRaw.Split("|".ToCharArray());
                    Line.ERROR = "FASLE";
                    return directoryList;
                }
                catch (Exception ex)
                {
                    Line.ERROR = "TRUE";
                    CL_TRAVAIL.Instance.LOG("ERROR 2 = " + ex.ToString());
                }
                /* Return an Empty string Array if an Exception Occurs */
                return new string[] { "" };
            }
            catch (Exception ex)
            {
                Line.ERROR = "TRUE";
                CL_TRAVAIL.Instance.LOG("ERROR 3 = " + ex.ToString());
                return new string[] { "" };
            }

        }



My error is at this line : ftpResponse = (FtpWebResponse)ftpRequest.GetResponse();

<pre>
10:40:29 - ERROR 3 = System.Net.WebException: La connexion sous-jacente a été fermée : Une erreur inattendue s'est produite lors de la réception.
   à System.Net.FtpWebRequest.CheckError()
   à System.Net.FtpWebRequest.SyncRequestCallback(Object obj)
   à System.Net.CommandStream.Abort(Exception e)
   à System.Net.CommandStream.CheckContinuePipeline()
   à System.Net.FtpDataStream.System.Net.ICloseEx.CloseEx(CloseExState closeState)
   à System.Net.FtpDataStream.Dispose(Boolean disposing)
   à System.IO.Stream.Close()
   à System.IO.StreamReader.Dispose(Boolean disposing)
   à WindowsService.FTP.directoryListSimple(ITEM Line, String directory)




What I have tried:

Hello

I use my code in windows form application and it work, but when i use it in my service application it does not work.

Somebody have an idea

Thank you

解决方案

Try setting the ftpwebrequest.timeout value to -1 (unlimited). The MS docs say it's set to that, but it's actually set to 100000 (100 seconds).


I use this and it's work i don't undurstand why???

public List<string> directoryListSimple(ITEM Line, string directory)
        {

            List<string> directoryList = new List<string>();

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(host + "/" + directory);
            request.Method = WebRequestMethods.Ftp.ListDirectory;

            // This example assumes the FTP site uses anonymous logon.  
            request.Credentials = new NetworkCredential(user, pass);
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
            //Console.WriteLine(reader.ReadToEnd());

            while (!reader.EndOfStream)
            {
                directoryList.Add(reader.ReadLine());
            }
            Console.WriteLine("Directory List Complete, status {0}", response.StatusDescription);

            reader.Close();
            responseStream.Close();
            response.Close();
            request = null;
            reader=null;
            responseStream=null;
            response = null;
            
            return directoryList;
        }


the soluce working with me

try
            {

                FtpWebRequest ftpReq = (FtpWebRequest)WebRequest.Create(host + "/" + remoteFile);
                ftpReq.UseBinary = true;
                ftpReq.Method = WebRequestMethods.Ftp.UploadFile;
                ftpReq.Credentials = new NetworkCredential(user, pass);

                byte[] b = File.ReadAllBytes(localFile);

                ftpReq.ContentLength = b.Length;
                using (Stream s = ftpReq.GetRequestStream())
                {
                    s.Write(b, 0, b.Length);
                }

                FtpWebResponse ftpResp = (FtpWebResponse)ftpReq.GetResponse();

                if (ftpResp != null)
                {
                    OUTILS.LOG("MSG FTP= " + ftpResp.StatusDescription.ToString());
                }
            }
            catch (Exception e)
            {
                OUTILS.LOG("ERROR START");
                OUTILS.LOG("MSG = " + e.ToString());
                OUTILS.LOG("ERROR END");
            }


这篇关于C#FTP和Windows服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆