现在在这个阶段我想知道是否有任何合适的方法来
检查url中的错误
您可以使用以下方法检查您的 Uri 是否有效
public static bool URLValidatorMethod(string strURL)
{
Uri uri;
return Uri.TryCreate(strURL, UriKind.RelativeOrAbsolute, out uri);
}
问)TryCreate 究竟做了什么?
A) 使用指定的 System.String 实例和 System.UriKind 创建一个新的 System.Uri。并返回一个 System.Boolean 值,如果 System.Uri 已成功创建,则返回 true,否则返回 false。
您可以使用
检查网址是否有
http 或
https
return Uri.TryCreate(strURL, UriKind.RelativeOrAbsolute, out uri) && uri.Scheme == Uri.UriSchemeHttp || uri.Scheme == Uri.UriSchemeHttps;
或
public static bool URLValidatorMethod(string strURL)
{
return Uri.IsWellFormedUriString(strURL, UriKind.RelativeOrAbsolute); ;
}
问)IsWellFormedUriString 究竟做了什么?
A) 通过尝试用字符串构造 URI 来指示字符串是否格式正确,并确保字符串不需要进一步转义。
停止下载文件,保持前一个文件不变
映射的地方
首先通过上述方法检查您的网址是否有效,如果有效则将其保存到文件夹中,否则忽略它
这样,您之前下载的文件将不再受到影响,并且它在您映射的位置上是安全的,例如
string url = "https://www.google.com.pk/";
if (URLValidatorMethod(url))
{
webClient.DownloadFile(url, Server.MapPath("~/App_Data/New_folder/Summary.csv"));
}
else
{
//Do code here that you want
}
已编辑:
try
{
string url = "https://www.google.com.pk/";
if (URLValidatorMethod(url))
{
webClient.DownloadFile(url, Server.MapPath("~/App_Data/New_folder/Summary.csv"));
}
else
{
//Do code here that you want
}
}
catch (Exception)
{
//Do code here if you want to execute if exception occurred
}
finally
{
//Do the code here that you want either exception occurred or not
//Means this code run always if exception comes or not
}
或
如果发生特定类型的异常或错误,您可以在编写代码时修改您的 catch 块
catch (Exception ex)
{
//You may check any particular exception and write your code
if (ex.GetType() == typeof(ArgumentNullException))
{
//Do code here
}
else
if (ex.GetType() == typeof(WebException))
{
//Do code here
}
else
if (ex.GetType() == typeof(NotSupportedException))
{
//Do code here
}
}
已编辑:
参考上面的详细答案,如果它对某人有帮助,这是对我有用的解决方案:
创建一个临时文件夹在那里下载您的文件,如果在下载过程中没有出现错误,它将文件从临时文件夹复制到原始位置并完成其余工作。否则,如果出现任何错误,将发送一封电子邮件指示错误,而其余代码将在实际代码流中执行而不会导致错误。
[HttpGet]
public ActionResult index(int OpCode)
{
try
{
System.IO.DirectoryInfo di = new DirectoryInfo(Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder"));
foreach (FileInfo csvfile in di.GetFiles())
{
csvfile.Delete();
}
MyWebClient webClient1 = new MyWebClient();
webClient1.DownloadFile("http://example.php", Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder/Summary.csv"));
}
catch (Exception)
{
return RedirectToAction("ImportSendMail");
}
var absolutePath = HttpContext.Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder/" + "Summary.csv");
if (System.IO.File.Exists(absolutePath))
{
System.IO.DirectoryInfo di2 = new DirectoryInfo(Server.MapPath("~/App_Data/TempPSC/PscData"));
foreach (FileInfo csvfile in di2.GetFiles())
{
csvfile.Delete();
}
String sourceFile = Server.MapPath("~/App_Data/TempPSC/PscData/Temp_folder/Summary.csv");
String destFile = Server.MapPath("~/App_Data/TempPSC/PscData/abc" + ".csv");
System.IO.File.Copy(sourceFile, destFile, true);
}
{
//Rest of the default code that you want to run
}
return View();
}