简体   繁体   中英

Check whether a folder exists on FTP server before uploading to that folder

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();
            }

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
        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM