如何用.NET 3.5实现客户端申请从服务器端下载一个文件?
发布网友
发布时间:2022-04-28 13:24
我来回答
共1个回答
热心网友
时间:2022-04-27 10:52
用FTP协议啊
引用:
System.Net
以下一些代码基于一些全局变量:
My.Resources.FTPRoot //string型 的FTP根目录URL
App.FTPCredential //NetworkCredential型 包含了服务器的登入帐号、密码
App.LocalRoot //string型 本地储存位置URL
这里我写了一个FTP下载的函数:
public static void FTPDownload(string path)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(My.Resources.FTPRoot + path);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = App.FTPCredential;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string data = reader.ReadToEnd();
reader.Close();
response.Close();
StreamWriter sw = new StreamWriter(App.LocalRoot + @"\" + path.Substring(1));
sw.Write(data);
sw.Close();
}
FTP上传:
public static void FTPUpload(string sorce)
{
string target = "/" + sorce.Substring(1);
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(My.Resources.FTPRoot + target);
request.Method = WebRequestMethods.Ftp.UploadFile;
request.Credentials = App.FTPCredential;
StreamReader sourceStream = new StreamReader(App.LocalRoot+sorce);
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();
}
或者直接利用FTP协议把远端文件的数据读到本机内存(有时候也蛮有用,这样本地不会出现文件,那个下载函数改的)
public static string FTPRead(string path)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(My.Resources.FTPRoot + path);
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = App.FTPCredential;
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
string data = reader.ReadToEnd();
reader.Close();
response.Close();
return data;
}
这最基本的,看看吧