Skip to main content
 首页 » 编程设计

c#之检查 FTP 上是否存在文件之不知道文件名

2024年02月06日14zhujiabin

我在 FTP 服务器上收到一个文件,文件名是动态生成的。我正在尝试编写一个程序来检查服务器上是否存在任何文件。

        string userName = Dts.Variables["User::SFTPUsername"].Value.ToString(); 
        string password = Dts.Variables["User::SFTPPassword"].Value.ToString(); 
        **string fileName = Dts.Variables["User::FilePattern"].Value.ToString();** 
        string ftpURL = String.Format("ftp://11.11.11/upload/{0}", fileName); 
 
            WebClient request = new WebClient(); 
            request.Credentials = new NetworkCredential(userName, password); 
 
 
            FtpWebRequest ftpRequest = (FtpWebRequest)WebRequest.Create(ftpURL); 
            ftpRequest.Method = WebRequestMethods.Ftp.GetFileSize; 
            ftpRequest.Credentials = new NetworkCredential(userName, password); 
 
            using (FtpWebResponse ftpResponse = (FtpWebResponse)ftpRequest.GetResponse()) 
            { 
                byte[] newFileData = request.DownloadData(ftpURL.ToString()); 
                string fileString = System.Text.Encoding.UTF8.GetString(newFileData); 
 
                string strexist = String.Format("exist"); 
                MessageBox.Show(strexist); 
                Dts.Variables["User::FileExists"].Value = true; 
            } 

只有当我指定“文件名”时,这才有效。无论如何我可以进行通配符搜索(“*.txt”)或搜索上传文件夹中是否有任何文件?

感谢任何帮助!!

请您参考如下方法:

您可以列出来自 FTP 的文件名。喜欢下面...

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpURL); 
            request.Method = WebRequestMethods.Ftp.ListDirectory;  
 
            FtpWebResponse response = (FtpWebResponse) request.GetResponse(); 
            using (Stream respStream = response.GetResponseStream()) 
            { 
                StreamReader reader = new StreamReader(respStream); 
                //Read each file name from the response 
                for (string fname = reader.ReadLine(); fname != null; fname = reader.ReadLine()) 
                { 
                    // Add the file name into a list 
                } 
            } 

如果列表计数为 0,则没有可用文件。此外,您将从单个请求中获取列表中的每个文件名。

使用foreach 循环 迭代列表值。并将上述代码作为方法。将文件名传递给方法。

您还可以确定特定文件名是否存在于列表中。

注意:在上面的代码中无需提供文件名到Url。 p>