0

I've checked other posts on this topic, but I can't seem to figure out the fundamentals of checking whether or not a directory exists on an FTP server before trying to upload a file there.

With the following code I get an exception when trying to upload to a folder that already exists. I feel that it shouldn't be too hard to just use some kind of folder.Exists before creating the directory, but I can't get it to work. Any ideas?

Upload method as of now:

        String id = Request.QueryString["ID"];
        String path = Server.MapPath("~/temp/");
        String filename = Path.GetFileName(fuPicture.PostedFile.FileName);

        if (fuPicture.HasFile)
        {
            try
            {
                fuPicture.PostedFile.SaveAs(path + fuPicture.FileName);
            }
            catch (Exception ex)
            {
                lblFeedback.Text = "Fel vid uppladdning";
            }
            path += fuPicture.FileName;

            String ftpServer = "ftp://xxx";

            String userName = "xx";
            String password = "xx";

            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(new Uri("ftp://xx/" + id));

            // I want to implement an if-condition here 
            // whether or not the folder exists
                request.Method = WebRequestMethods.Ftp.MakeDirectory;
                request.Credentials = new NetworkCredential(userName, password);

            using (var resp = (FtpWebResponse)request.GetResponse())
            {
                WebClient client = new WebClient();
                client.Credentials = new NetworkCredential(userName, password);
                client.UploadFile(ftpServer + "/" + id + "/" + new FileInfo(path).Name, "STOR", path);
                resp.Close();
            }
Shaharyar
  • 12,254
  • 4
  • 46
  • 66
guitarzero
  • 545
  • 9
  • 18

1 Answers1

0

Try listing directory ListDirectory, if not found then create MakeDirectory

   request.Method = WebRequestMethods.Ftp.ListDirectory;
   request.Credentials = new NetworkCredential(userName, password);

   try
    {
        using (request.GetResponse())
        {
            //continue
        }
    }
    catch (WebException)
    {
        request.Method = WebRequestMethods.Ftp.MakeDirectory;
        using (request.GetResponse())
        {
            //continue
        }
    }
Murali Murugesan
  • 22,423
  • 17
  • 73
  • 120