上传到 ftp asp.net

时间:2023-03-31
本文介绍了上传到 ftp asp.net的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

是否可以使用 ASP.NET 将文件直接上传到 ftp 帐户文件夹中?

Is it possible to upload a file directly into an ftp account folder with ASP.NET ?

例如我点击浏览,选择要上传的文件,当我点击上传"按钮时,它应该将其直接保存到另一个 Web 服务器上的文件夹中,该服务器位于其他地方,而不是用于上传的服务器.

E.g. I click on browse, select a file to upload and when I click "upload" button, It should save it directly to the folder on another web server located at somewhere else other then the server that is being used to upload.

推荐答案

    /// <summary>
    /// Example call : if (FtpUpload(FileUploadControl1, "ftp.my.com/somePathDir", @"user", "pass!", "domain"))
    /// </summary>
    /// <param name="file"></param>
    /// <param name="ftpServer"></param>
    /// <param name="username"></param>
    /// <param name="ftpPass"></param>
    /// <returns></returns>
    private bool FtpUpload(FileUpload file, string ftpServer, string username, string ftpPass, string domainName = "")
    {
        // ftp://domainuser:password@ftpserver/url-path
        // If you are a member of a domain, then "ftp://domain-nameusername:password@url-path" may fail because the backslash () is sent in as a literal character and Internet Explorer incorrectly looks for a file instead of parsing a Web address. Changing the backslash () in the domain-nameusername to domainname%5Cusername works correctly.

        try
        {
            string ftpAddres;
            if (domainName != string.Empty)
                ftpAddres = "ftp://" + domainName + @"%5C" + username + ":" + ftpPass + "@" + ftpServer + "/" + file.FileName;
            else
                ftpAddres = "ftp://" + username + ":" + ftpPass + "@" + ftpServer + "/" + file.FileName;

            using (var webClient = new System.Net.WebClient())
            {
                webClient.UploadData(new Uri(ftpAddres), file.FileBytes);
            }

        }
        catch (Exception e)
        {
            throw new Exception(e.Message, e);
        }
        return true;
    }

这篇关于上传到 ftp asp.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何在 FTP 服务器上复制文件? 下一篇:C# 使用 FTP 上传整个目录

相关文章