我的代码工作正常,但有时会出现The type initializer for 'System.Net.FtpWebRequest' threw an exception.
错误。我正在从FTP服务器下载一个csv,这是我的代码的一部分。
public static void Download(string FilePath)
{
FtpWebResponse response=null;
try
{
FtpWebRequest reqFTP;
//Setting FTP attributes
ftpserver = ConfigurationManager.AppSettings["FTPDomain"].ToString() + "//" + ConfigurationManager.AppSettings["FTPFileName"].ToString();
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpserver));
reqFTP.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["FTPUser"], ConfigurationManager.AppSettings["FTPPass"]);
reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;
reqFTP.UseBinary = true;
reqFTP.Proxy = null;
reqFTP.UsePassive = false;
response = (FtpWebResponse)reqFTP.GetResponse();
Stream responseStream = response.GetResponseStream();
//Delete File if Exist
//Copying file
FileStream writeStream = new FileStream(FilePath, FileMode.Create);
int Length = 2048;
Byte[] buffer = new Byte[Length];
int bytesRead = responseStream.Read(buffer, 0, Length);
while (bytesRead > 0)
{
writeStream.Write(buffer, 0, bytesRead);
bytesRead = responseStream.Read(buffer, 0, Length);
}
writeStream.Close();
response.Close();
// HomeController.SalesStatus = "ok";
}
catch (WebException ex)
{
}
通常我在这一行reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpserver));
得到错误然后我需要关闭我的视觉工作室并重新启动解决方案然后它工作正常。有任何建议如何解决这个问题?