温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

C# 保存远程文件到本地

发布时间:2020-07-24 12:18:42 来源:网络 阅读:1112 作者:demon2012d 栏目:编程语言
/// <summary>
/// 保存远程文件到本地
/// </summary>
/// <param name="url">远程文件URL</param>
/// <param name="file">保存的本地路径</param>
/// <returns></returns>
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();
    }


向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI