本文共 2445 字,大约阅读时间需要 8 分钟。
自定义一个方法
public static string MapPath(string strPath) { if (System.Web.HttpContext.Current != null) { return System.Web.HttpContext.Current.Server.MapPath(strPath); } else //非web程序引用 { strPath = strPath.Replace("/", ""); strPath = strPath.Replace("~", ""); if (strPath.StartsWith("\\")) { strPath = strPath.TrimStart('\\'); } return System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, strPath); } }
-------------------------------------------------------------------------------------------------------------------------------
private HttpWebRequest CreateRequest(string path, string queryString = null)
{ if (!string.IsNullOrWhiteSpace(queryString) && !queryString.StartsWith("?")) queryString = "?" + queryString;var url = new Uri(BaseUrl, path + queryString).AbsoluteUri;
var request = (HttpWebRequest)WebRequest.Create(url);
request.Headers["Authorization"] = AuthorizationKey;
request.Timeout = TimeoutSeconds == System.Threading.Timeout.Infinite ? TimeoutSeconds : TimeoutSeconds * 1000;return request;
}public bool SaveResponseContentToCSV(String path, String queryString = null)
{ var request = CreateRequest(path, queryString); var requestTrace = string.Empty;using (var response = (HttpWebResponse)request.GetResponse())
{ try { var fileType = response.ContentType; var index = response.Headers["Content-Disposition"].IndexOf("=") + 1; var fileName = response.Headers["Content-Disposition"].Substring(index);Stream respStream = response.GetResponseStream();
int length = (int)response.ContentLength; BinaryReader br = new BinaryReader(respStream); FileStream fs; //var localFilePath = System.Web.HttpContext.Current.Server.MapPath("\\dailyClickActivity" + "\\" + System.DateTime.Now.ToLongTimeString()); //AppDomain.CurrentDomain.BaseDirectory var localFilePath = System.IO.Path.Combine(Environment.CurrentDirectory, "/dailyClickActivity" + "/" + System.DateTime.Now.ToString("yyyyMMdd")); if (!Directory.Exists(localFilePath)) Directory.CreateDirectory(localFilePath);fs = File.Create(string.Format("{0}/{1}", localFilePath, fileName));
fs.Write(br.ReadBytes(length), 0, length);br.Close();
fs.Close();return true;
} catch (Exception ex) { requestTrace += ex.Message; throw; } finally { //TracerLogger.Log(requestTrace, EventLogEntryType.Information, Constants.RoleNameAdFabricClick); Console.WriteLine(string.Format("{0},{1},{2}", requestTrace, EventLogEntryType.Information, Constants.RoleNameAdFabricClick));}
} }
转载地址:http://qojab.baihongyu.com/