【问题标题】:Downloading a file from internet to ASP.NET MVC web application将文件从 Internet 下载到 ASP.NET MVC Web 应用程序
【发布时间】:2012-09-27 23:55:06
【问题描述】:

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

using System.Net;

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

【问题讨论】:

    标签: c# asp.net-mvc iis


    【解决方案1】:

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

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

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

    还要注意,WebClient 类实现了 IDisposable,所以你应该使用 dispose 或使用 struct。
    我渴望你阅读一些 c# 的命名约定(局部变量通常以小写字母开头)。

    【讨论】:

    • 更正了有问题的和我的代码中指出的错误。
    【解决方案2】:

    您可以通过 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();
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-05
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多