C#リモートファイルをローカルに保存
2382 ワード
///
///
///
/// URL
///
///
public bool DownloadFile(string url, string file)
{
try
{
(new System.Net.WebClient()).DownloadFile(url,file);
return true;
}
catch { }
return false;
}
public void Download(string strURL,string strName)
{
string strRootDir = "D:\\DownLoadRecode";
if (!Directory.Exists(strRootDir))
{
Directory.CreateDirectory(strRootDir);
}
WebClient client = new WebClient();
string strFileName = string.Empty;
string strFileDir = string.Empty;
string strSavePath = string.Empty;
string[] arrName = strName.Split('/');
if (arrName != null && arrName.Length > 1)
{
strFileDir = arrName[0];
strFileName = arrName[1];
strSavePath = strRootDir + "\\" + strFileDir;
if (!Directory.Exists(strSavePath))
{
Directory.CreateDirectory(strSavePath);
}
}
else
{
strFileName = strName;
strSavePath = strRootDir + "\\Temp";
if (!Directory.Exists(strSavePath))
{
Directory.CreateDirectory(strSavePath);
}
}
strSavePath += "\\" + strFileName;
if (!File.Exists(strSavePath))
{
client.DownloadFile(strURL, strSavePath);
}
FileInfo xFileInfo = new FileInfo(strSavePath);
Response.Clear(); //
Response.ClearHeaders(); //
Response.Buffer = false; // false
// HTTP MIME application/octet-stream
Response.ContentType = "audio/x-wav";
Response.Charset = "GB2312";
Response.ContentEncoding = Encoding.UTF8;
// HTTP
Response.AppendHeader("Content-Disposition",
"p_w_upload;filename=" + HttpUtility.UrlEncode(strFileName));
Response.AppendHeader("Content-Length", xFileInfo.Length.ToString());
// HTTP
Response.WriteFile(strSavePath);
Response.Flush();
Response.End();
}