2

参考我较早的问题,关于从服务器下载文件并正确处理异常。我很肯定我已经解决了这个问题,然后以经典的编程方式,几天后回来沮丧地发现它坏了:-(


更新代码:

private static void GoGetIt(HttpContext context)
    {
        var directoryInfoOfWhereTheDirectoryFullOfFilesShouldBe = new FileInfo(......);
                var name = SomeBasicLogicToDecideName();

            //if (!directoryInfoOfWhereTheDirectoryFullOfFilesShouldBe.RefreshExists())
            //{
            //  throw new Exception(string.Format("Could not find {0}.", name));
            //}

            var tempDirectory = ""; //Omitted - creates temporary directory

            try
            {
                directoryInfoOfWhereTheDirectoryFullOfFilesShouldBe.CopyAll(tempDirectory);
                var response = context.Response;
                response.ContentType = "binary/octet-stream";
                response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.zip", name));
                ZipHelper.ZipDirectoryToStream(tempDirectory, response.OutputStream);
                response.End();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
                context.Response.StatusCode = 404;
            }
            finally
            {
                tempDirectory.DeleteWithPrejudice();
            }
        }

这工作正常,并返回 zip,否则如果文件不存在返回 404。然后在客户端我可以处理这个:

public bool Download()
{   
 try
                {
                    using (var client = new WebClient())
                    {
                        client.DownloadFile(name, tempFilePath);
                    }

                }
                catch (Exception)
                {
                    fileExists = false;
                }
return fileExists;
    }

但现在的问题是两件事。

1) 我得到 System.Threading.ThreadAbortException: 线程在服务器端 try-catch 块中被中止。通常这只是一个未找到文件的异常。我不知道抛出什么或为什么抛出新异常?

2) 现在在服务器端抛出了一个不同的异常,而不是找不到文件,看来我不能为应用程序使用这个设置,因为回到客户端,任何异常都被假定为 filenotfound。

任何帮助,尤其是有关为什么抛出此 ThreadAbortException 的信息!?!?非常感激。干杯

4

1 回答 1

3

问题是Response.End()抛出一个 ThreadAbortException:这就是它结束请求的方式。完全摆脱那个电话,你不需要它。

于 2010-03-30T03:21:29.750 回答