The following code to check if a file exists on a server does not work
- by xplorer2k
Hi Everyone,
I found the following code to check if a file exists on a server, but is not working for me.  It tells me that "test1.tx" does not exist even though the file exists and its size is 498 bytes.
If I try with Ftp.ListDirectory it tells me that the file does not exist.
If I try with Ftp.GetFileSize it does not provide any results and the debugger's immediate gives me the following message: A first chance exception of type 'System.Net.WebException' occurred in System.dll.
Using "request.UseBinary = true" does not make any difference.
I have posted this same question at this link:  http://social.msdn.microsoft.com/Forums/en-US/ncl/thread/89e05cf3-189f-48b7-ba28-f93b1a9d44ae
Could someone help me how to fix it?
   private void button1_Click(object sender, EventArgs e)
    {
        string ftpServerIP = txtIPaddress.Text.Trim();
        string ftpUserID = txtUsername.Text.Trim();
        string ftpPassword = txtPassword.Text.Trim();
        try
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create("ftp://" + ftpServerIP + "//tmp/test1.txt");
            request.Method = WebRequestMethods.Ftp.ListDirectory;
            //request.Method = WebRequestMethods.Ftp.GetFileSize;
            request.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
            //request.UseBinary = true;
            using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
            {
                // Okay.
                textBox1.AppendText(Environment.NewLine);
                textBox1.AppendText("File exist");
            }
        }
        catch (WebException ex)
        {
            if (ex.Response != null)
            {
                FtpWebResponse response = (FtpWebResponse)ex.Response;
                if (response.StatusCode == FtpStatusCode.ActionNotTakenFileUnavailable)
                {
                    // Directory not found. 
                    textBox1.AppendText(Environment.NewLine);
                    textBox1.AppendText("File does not exist");
                }
            }
        }
    }
Thanks very much,
xplorer2k