【发布时间】:2015-03-28 18:06:58
【问题描述】:
首先,我确实尝试为我的问题寻找答案,但没有找到。
我一直在制作一个程序,其中我的本地文本文件和位于 FTP 服务器中的在线文本文件会自动相互更新。文本文件包含名称列表。此应用程序旨在供不同机器同时使用,并且可以在列表中添加和删除名称。
在附加算法的帮助下,我能够合并本地和在线文本文件,即使在离线使用时也不会出现问题,并且在有互联网连接时更新(使用其他本地文件)。
现在的问题是,90% 的时间里一切正常。但是,有时从 FTP 服务器下载的文本文件会返回一个空白文本文件,即使它不是。我注意到当我的应用程序很难检查互联网连接(Pinging google.com)时,最有可能发生这种情况。这将导致列表被完全删除,因为我的应用程序会将其解释为“使用该应用程序的其他用户删除了列表”。
这是我从 FTP 服务器下载的方法:
public Boolean DownloadFile(string uri, string path)
{
FtpWebRequest request = (FtpWebRequest)WebRequest.Create(uri);
request.UsePassive = true;
request.KeepAlive = true;
request.UseBinary = true;
request.Proxy = null;
request.Timeout = 5000;
request.Method = WebRequestMethods.Ftp.DownloadFile;
request.Credentials = new NetworkCredential(this.username, this.password);
try
{
FtpWebResponse response = (FtpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader reader = new StreamReader(responseStream);
StringBuilder sb = new StringBuilder();
sb.AppendLine(reader.ReadToEnd());
File.WriteAllText(path, sb.ToString());
reader.Close();
response.Close();
return true;
}
catch (Exception e )
{
MessageBox.Show("FTPHANDLER DOWNLOAD FILE:"+e.ToString());
return false;
}
}
我用来检查网络连接的方法:
private static bool CheckForInternetConnection()
{
try
{
Ping myPing = new Ping();
String host = "google.com";
byte[] buffer = new byte[32];
int timeout = 15000;
PingOptions pingOptions = new PingOptions();
PingReply reply = myPing.Send(host, timeout, buffer, pingOptions);
return (reply.Status == IPStatus.Success);
}
catch (Exception e)
{
//MessageBox.Show(e.ToString());
return false;
}
}
我就是这样称呼它的。我已经提供了安全措施以防止这种情况发生,但它仍然会发生。
public void Update()
{
if(CheckForInternetConnection()){
if (DownloadFile(uri,path))
{
char[] charsToTrim = { '\r', '\n' };
string onlineFile = File.ReadAllText(path).TrimEnd(charsToTrim);
if (onlineConfigFile.Equals("") || onlineConfigFile == null)
MessageBox.Show("Downloaded file is empty");
//still do stuff here regardless of the message
//If the other user really do intend to delete the list
}
}
}
更新方法在不同的线程中执行。
至于我在这里的第一篇文章,很抱歉它变得很长。我确实尝试过简短,但不想错过任何细节。
【问题讨论】:
-
我现在正在考虑使用“lock”,因为 Update 方法每 5 秒调用一次,并且每个方法都在不同的线程中运行。这将确保安全措施的逻辑不会被其他线程利用。
标签: c# download ftp text-files