2012-09-27 33 views
0

對於我目前正在使用的Web應用程序,我想從互聯網下載文件到我的Web服務器。 我可以使用下面的代碼將文件下載到Web服務器的硬盤驅動器,我應該如何設置到目標路徑才能使其工作。我們計劃在共享主機環境中託管此網站。
將文件從互聯網下載到ASP.NET MVC Web應用程序

using System.Net; 

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

回答

1

我認爲常見的方式做到這一點是這樣的:

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

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

還要注意,那WebClient類實現IDisposable,所以你應該使用處置或使用結構。
我希望您閱讀c#的一些命名約定(本地變量通常以小寫字母開頭)。

+0

糾正錯誤尖,無論是在的問題,在我的代碼。 – Dhananjaya

0

您可以從您的計算機通過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(); 
    } 
相關問題