如何比较catch error.Message到主机字符串?

时间:2014-11-14 08:47:27

标签: c# .net winforms

这是代码:

try
{
    BackgroundWorker bw = sender as BackgroundWorker;
    f = e.Argument as FtpSettings;
    string UploadPath = String.Format("{0}/{1}{2}", f.Host, f.TargetFolder == "" ? "" : f.TargetFolder + "/", Path.GetFileName(f.SourceFile));
    if (!UploadPath.ToLower().StartsWith("ftp://"))
        UploadPath = "ftp://" + UploadPath;
    FtpWebRequest request = (FtpWebRequest)WebRequest.Create(UploadPath);
    request.UseBinary = true;
    request.UsePassive = f.Passive;
    request.Method = WebRequestMethods.Ftp.UploadFile;
    request.Credentials = new NetworkCredential(f.Username, f.Password);
    long FileSize = new FileInfo(f.SourceFile).Length;
    string FileSizeDescription = GetFileSize(FileSize);
    int ChunkSize = 4096, NumRetries = 0, MaxRetries = 50;
    long SentBytes = 0;
    byte[] Buffer = new byte[ChunkSize];
    using (Stream requestStream = request.GetRequestStream())
    {
        using (FileStream fs = File.Open(f.SourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            int BytesRead = fs.Read(Buffer, 0, ChunkSize);
            while (BytesRead > 0)
            {
                try
                {
                    if (bw.CancellationPending)
                        return;

                    requestStream.Write(Buffer, 0, BytesRead);

                    SentBytes += BytesRead;

                    string SummaryText = String.Format("Transferred {0} / {1}", GetFileSize(SentBytes), FileSizeDescription);
                    bw.ReportProgress((int)(((decimal)SentBytes / (decimal)FileSize) * 100), SummaryText);
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("Exception: " + ex.ToString());
                    if (NumRetries++ < MaxRetries)
                    {
                        fs.Position -= BytesRead;
                    }
                    else
                    {
                        throw new Exception(String.Format("Error occurred during upload, too many retries. \n{0}", ex.ToString()));
                    }
                }
                BytesRead = fs.Read(Buffer, 0, ChunkSize);
            }
        }
    }
    using (FtpWebResponse response = (FtpWebResponse)request.GetResponse())
        System.Diagnostics.Debug.WriteLine(String.Format("Upload File Complete, status {0}", response.StatusDescription));
}
catch (Exception error)
{
    er = "The remote name could not be resolved: " + f.Host;
    if (error.Message == "The remote name could not be resolved: " + f.Host)
    {
        ConnectionError = "Error: Please check the ftp address";
    }
}

在底部我正在做:

if (error.Message == "The remote name could not be resolved: " + f.Host)

问题是来自示例的error.Message包含:

无法解析远程名称:'ftp.test.comdfdsfdsf'

而f.Host包含:

ftp.test.comdfdsfdsf

在f.Host中它错过了'' 或者可能是error.Message''

但他们不一样。

我需要这个比较以便稍后使用Form1中的ConnectionError全局变量来向用户表明ftp地址有问题。

1 个答案:

答案 0 :(得分:1)

处理此问题的正确方法是将其缩小到抛出的异常类型并使用该属性。

在这种特殊情况下,这是正确的方法:

catch (WebException ex)
{
    switch (ex.Status)
    {
        case WebExceptionStatus.NameResolutionFailure:
            ConnectionError = "Error: Please check the ftp address";

        case WebExceptionStatus.....
    }
}

您根本不需要进行字符串比较。