繁体   English   中英

将文件从Internet下载到ASP.NET MVC Web应用程序

[英]Downloading a file from internet to ASP.NET MVC web application

对于当前正在使用的Web应用程序,我想将文件从Internet下载到我的Web服务器。 我可以使用以下代码将文件下载到Web服务器的硬盘驱动器,我应该将其设置为目标路径以使其正常工作。 我们计划在共享托管环境中托管此网站。

using System.Net;

using(var client = new WebClient())
{
    client.DownloadFile("http://file.com/file.txt", @"C:\file.txt");
}

我认为通常的做法是这样的:

string appdataFolder = AppDomain.CurrentDomain.GetData("DataDirectory").ToString();

要么

string appdataFolder = System.Web.HttpContext.Current.Server.MapPath(@"~/App_Data");

还要注意,WebClient类实现IDisposable,因此您应该使用dispose或struct。
而且,我希望您能阅读一些有关c#的命名约定(局部变量通常以小写字母开头)。

您可以通过ftp请求将其从计算机上传到服务器,

string _remoteHost = "ftp://ftp.site.com/htdocs/directory/";
    string _remoteUser = "site.com";
    string _remotePass = "password";
    string sourcePath = @"C:\";

    public void uploadFile(string name)
    {
        FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost +name+ ".txt");
        request.Method = WebRequestMethods.Ftp.UploadFile;

        request.Credentials = new NetworkCredential(_remoteUser, _remotePass);


        StreamReader sourceStream = new StreamReader(sourcePath + name+ ".txt");
        byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
        sourceStream.Close();
        request.ContentLength = fileContents.Length;

        Stream requestStream = request.GetRequestStream();
        requestStream.Write(fileContents, 0, fileContents.Length);
        requestStream.Close();

        FtpWebResponse response = (FtpWebResponse)request.GetResponse();

        response.Close();
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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