新创建的文件提供FileNotFound,直到ASP.NET站点已经过了5秒

时间:2015-01-15 15:28:12

标签: c# asp.net iis filenotfoundexception

用这个把头发拉了出来。

我进行了一次阻止调用,将docx转换为pdf以及网络共享上的原始文件。 该调用返回true表示成功。然后我尝试在文件上尝试File.Exists并得到错误的回复。现在我常常回复,因为文件确实存在,所以这是一个在上周左右出现的问题。缩小原因和/或改变是我正在努力做的事情。

我尝试的第一件事是(出于测试目的)将File.Exists放入循环并阻塞以每秒迭代循环。每个循环代表一次尝试,最多10次循环或10秒。我发现在大约5秒后,File.Exists会一直返回true,因此可以访问它。

在第一次File.Exists失败后,我已经添加了一些额外的测试检查,我发现该文件是由Directory.GetFiles列出的,FileIOPermission说我确实有权限,没有任何锁定,当我尝试File.Open是2或FILE_NOT_FOUND时来自Win32的HRESULT。

顺便说一句,这都是在IIS和ASP.NET之下。 Windows身份验证和模拟已打开。

为了弥补这种陌生感,在重建(或回收应用程序池)后,它会在第一次尝试时找到它。所有后续测试都会失败,直到5秒钟过去 其次,这在我的机器上工作正常,指向同一UNC路径上的同一文件,它总是立即找到该文件。

我将删除下面的一些测试代码以帮助概述

var stopwatch = new Stopwatch();
stopwatch.Start();
bool found = false;
int attempt = 1;
for (int i = 1; i <= 10; i++)
{
    if (File.Exists(targetRevision.PdfPath))
    {
        found = true;
        attempt = i;
        break;
    }
    else
    {
        if (i == 1)
        {
            var visibleFiles = Directory.GetFiles(Path.GetDirectoryName(targetRevision.PdfPath))
                .Aggregate((a, f) => a + Environment.NewLine + f);
            Logger.Log("Listing of visible files", LogTypeEnum.Debug, new Exception(visibleFiles));

            try
            {
                new System.Security.Permissions.FileIOPermission(
                System.Security.Permissions.FileIOPermissionAccess.Read, targetRevision.PdfPath).Demand();
            }
            catch (Exception e)
            {
                Logger.Log("Don't appear to have access to the file.", LogTypeEnum.Debug, e);
            }
            try
            {
                using (var pdfStream = File.Open(targetRevision.PdfPath, FileMode.Open))
                {

                }
            }
            catch (Exception e)
            {
                var hresult = Marshal.GetHRForException(e);
                var errorCode = hresult & ((1 << 16) - 1);

                Logger.Log("Can't seem to open the file. HRESULT " + hresult + ", errorCode " + errorCode, LogTypeEnum.Debug, e);
            }

            try
            {
                var lockingProcesses = FileUtil.WhoIsLocking(targetRevision.PdfPath);

                if (lockingProcesses.Any())
                {
                    Logger.Log("Listing of locking processes", LogTypeEnum.Debug, new Exception(
                    lockingProcesses
                        .Select(p => p.ProcessName)
                        .Aggregate((a, p) => a + Environment.NewLine + p)));
                }
                else
                {
                    Logger.Log("No locks found on PDF", LogTypeEnum.Debug);

                }
            }
            catch (Exception e)
            {
                Logger.Log("Failed to check for locking processes", LogTypeEnum.Debug, e);
            }
        }

        Thread.Sleep(1000);

        // thy eyes bleed - this is debug (NOT PRODUCTION CODE)
    }
}
stopwatch.Stop();

0 个答案:

没有答案