访问路径“Enrollments.zip”被拒绝,运行后台服务运行后

Posted

技术标签:

【中文标题】访问路径“Enrollments.zip”被拒绝,运行后台服务运行后【英文标题】:Access to the path 'Enrollments.zip' is denied, After running Background service running 【发布时间】:2018-10-24 06:12:44 【问题描述】:

重启电脑后,后台服务正常。如果我重新安装或对数据库进行了任何更改,我的 PC 访问路径“.zip”被拒绝。另一台 PC 上正在运行相同背景的另一件事。

两个后台服务在两台不同的 PC 上运行以交换数据。

代码如下:

    public void GetFilesFromWebAPIAndCountTemplates(DateTime startTime,DateTime endTime,string webAPIURL,string code,string localPath)
               
        ZipLocationsCount zipLocation = null;
        count = 0;
        if (startTime < endTime)
        
            WebApiCall apiCall = new WebApiCall();
            Thread.Sleep(10000);
            var zipByteResponse = apiCall.CallZipWebApi(webAPIURL, "api/ZIPEnrollmentsDownload/ZIPResponse?startTime=" + startTime + "&endTime=" + endTime+ "&locationCode="+code, null, Constants.Get);
            lgmr.Log(string.Concat(serviceName, " ", code, ": Get Response From WebAPI successfully"), LoggingManager.LogType.Info);

            if (zipByteResponse.Result != null && zipByteResponse.Result.Length > 0)
            
                string fileName = code + "_Enrollments.zip";

                try
                                       
                    ConvertIntoZipAndMoveToBackUp(localPath, fileName, zipByteResponse.Result, code);
                
                catch(Exception ex)
                
                    //GetFilesFromWebAPIAndCountTemplates(startTime, endTime, webAPIURL, code, localPath);  
                    ecount = 0;
                    strECount = "Fail to Zip";
                    lgmr.Log(string.Concat(serviceName, " ", code, " count:", ecount, ": Failed to Converted to ZIP", ex.StackTrace, ex.InnerException, ex.Message), LoggingManager.LogType.Error);
                    goto label1;
                

            
            else
            
                ecount = 0;
                if(ecount == 0)
                
                    strECount = "No Enrolments";
                
                lgmr.Log(string.Concat(serviceName, " ", code, ": No Enrollments"), LoggingManager.LogType.Info);
            
        
        else
        
            lgmr.Log(string.Concat(serviceName, " ",code, ": Start Date Should be lass than End Date"), LoggingManager.LogType.Info);
        

        FPSyncHistory fpSync = new FPSyncHistory();
        fpSync.LocationCode = code;
        fpSync.FromDate = startTime;
        fpSync.ToDate = endTime;
        fpSync.FPExported = ecount;
        fpSync.Status = true;
        fpSync.CreatedBy = 1;
        fpSync.CreatedOn = DateTime.Now;
        fPSyncHistories.Add(fpSync);

        label1:
        zipLocation = new ZipLocationsCount()  LocationCode = code, FromDate = startTime, ToDate = endTime, EnrollmentsCount = strECount ;
        if (zipLocation.FromDate < zipLocation.ToDate)
        
            zipLocationsCounts.Add(zipLocation);
        
       

上面的方法我正在调用另一个方法

 public void GetZipResponseFromWebAPI()
    
        try
                        
            zipLocationsCounts = new List<ZipLocationsCount>();
            fPSyncHistories = new List<FPSyncHistory>();
            DateTime sTime = new DateTime();
            DateTime startTime = new DateTime();
            DateTime eTime = new DateTime();
            DateTime endTime = new DateTime();


            foreach (FPSyncLocationDetail fpLocation in tmlEntity.FPSyncLocationDetails)
                               
                var findHistory = tmlEntity.FPSyncHistories.FirstOrDefault(x => x.LocationCode == fpLocation.Code);
                if (findHistory == null)
                                      
                    if(fpLocation.Status == true)
                    
                        sTime = DateTime.Now.AddDays(-1);
                        startTime = new DateTime(sTime.Year, sTime.Month, sTime.Day, 00, 00, 00);
                        eTime = DateTime.Now.AddDays(-1);
                        endTime = new DateTime(eTime.Year, eTime.Month, eTime.Day, 23, 59, 59);

                        GetFilesFromWebAPIAndCountTemplates(startTime,endTime,fpLocation.WebAPIURL,fpLocation.Code,fpLocation.LocalFPFolderPath);
                    
                
                else if (findHistory != null)
                
                    var locationLastDates = from n in tmlEntity.FPSyncHistories
                                            group n by n.LocationCode into g
                                            select new  LocationCode = g.Key, ToDate = g.Max(t => t.ToDate) ;
                    foreach (var loc in locationLastDates)
                    
                        if (fpLocation.Code == loc.LocationCode)
                        
                            if (fpLocation.Status == true)
                            
                                sTime = loc.ToDate.AddDays(1);
                                startTime = new DateTime(sTime.Year, sTime.Month, sTime.Day, 00, 00, 00);
                                eTime = DateTime.Now.AddDays(-1);
                                endTime = new DateTime(eTime.Year, eTime.Month, eTime.Day, 23, 59, 59);

                                GetFilesFromWebAPIAndCountTemplates(startTime, endTime, fpLocation.WebAPIURL, fpLocation.Code, fpLocation.LocalFPFolderPath);
                            
                        
                    
                
                                          
        
        catch (Exception ex)
        
            string InnerException = ex.InnerException != null ? ex.InnerException.ToString() : "";
            lgmr.Log(string.Concat("Error at GetZipResponseFromWebAPI", ex.StackTrace, ex.InnerException, ex.Message), LoggingManager.LogType.Error);
            return;
        
    

下面终于CallWebAPI方法逻辑了

 public async Task<byte[]> CallZipWebApi(String WebApiUri, String uri, StringContent obj, string type)
               
        try
        
            count++;
           HttpResponseMessage resMeg;
            using (var client = new HttpClient())
            
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
                client.BaseAddress = new Uri(WebApiUri);
                lgmr.Log(string.Concat(uri,": Sending Request to WebAPI"), LoggingManager.LogType.Info);
                if (type == Constants.Get)
                
                    resMeg =await client.GetAsync(uri);
                
                else
                
                    resMeg =await client.PostAsync(uri, obj);
                
                lgmr.Log(string.Concat(uri,": Receive Response From WebAPI"), LoggingManager.LogType.Info);
                var Bytes =await resMeg.Content.ReadAsByteArrayAsync();
                //byte[] mybyteArray = null;
                //Task<byte[]> Bytes = ProcessURLAsync(uri,client);
                lgmr.Log(string.Concat(": Read the Data from WebAPI Response"), LoggingManager.LogType.Info);                               
                return Bytes;
            
        


public void ConvertIntoZipAndMoveToBackUp(string localPath, string fileName, byte[] zipByteResponse, string code)
    
        string Destinationpath = ConfigurationManager.AppSettings["OtherEnrollmentsBackUpPath"] + "\\" + code;
        try
                       
            ZipArchive archive = null;
            if (File.Exists(localPath + "\\" + fileName))
            
                File.Delete(localPath + "\\" + fileName);
            
            archive = ZipFile.Open(localPath + "\\" + fileName, ZipArchiveMode.Create);
            archive.Dispose();
            lgmr.Log(string.Concat(serviceName, " ", code, ": Zip File Created", localPath + "\\" + fileName), LoggingManager.LogType.Info);
            File.WriteAllBytes(localPath + "\\" + fileName, zipByteResponse);

            lgmr.Log(string.Concat(serviceName, " ", code, ": Download Zipfile from the WebAPI Response"), LoggingManager.LogType.Info);

            archive = ZipFile.OpenRead(localPath + "\\" + fileName);
            ecount = archive.Entries.Count(x => !string.IsNullOrWhiteSpace(x.Name));
            strECount = ecount.ToString();
            lgmr.Log(string.Concat(serviceName, " ", code, ": Files Count: ",ecount, localPath + "\\" + fileName), LoggingManager.LogType.Info);
            foreach (ZipArchiveEntry entry in archive.Entries)
            
                if (File.Exists(localPath + "\\" + entry.Name))
                
                    File.Delete(localPath + "\\" + entry.Name);
                
                entry.ExtractToFile(localPath + "\\" + entry.Name);
            
            archive.Dispose();


            File.Move(localPath + "\\" + fileName, Destinationpath + "\\" + code + string.Format("Enrollments-0:yyyy-MM-dd_hh-mm-ss.fff.zip", DateTime.Now));
        
        catch (Exception ex)
        
            //File.Delete(localPath + "\\" + fileName);
            //File.Move(localPath + "\\" + fileName, Destinationpath + "\\" + code + string.Format("ZipErrorEnrollments-0:yyyy-MM-dd_hh-mm-ss.fff.zip", DateTime.Now));
            ecount = 0;               
            lgmr.Log(string.Concat(serviceName, " ", code, " ECount:", ecount, ": Failed to ZIP", localPath + "\\" + fileName, "Resend the Request to WebAPI ", ex.Message), LoggingManager.LogType.Info);
            throw ex;
        
    

【问题讨论】:

【参考方案1】:

一些你可以看的东西。

首先,使用using 语句创建存档,这将确保它被处理掉。

其次,你为什么要检查文件是否存在,删除它,然后用ZipFile创建它只是为了用File写它?看this

第三,使用 Path 类。它将确保您所有的反斜杠都是正确的,并且看起来更整洁。

四、检查文件夹中是否可以创建文件

检查这段代码是否给你同样的结果。

public void ConvertIntoZipAndMoveToBackUp(string localPath, string fileName, byte[] zipByteResponse, string code)
    
        string Destinationpath = Path.Combine(ConfigurationManager.AppSettings["OtherEnrollmentsBackUpPath"], code);
        try
                       
            fileName = Path.GetFileNameWithoutExtension(fileName) + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss.fff") + ".zip";  //This will ensure that you have a unique filename to create
            File.WriteAllBytes(Path.Combine(localPath, fileName), zipByteResponse);
            lgmr.Log(string.Concat(serviceName, " ", code, ": Zip File Created and Downloaded from the WebAPI Response", Path.Combine(localPath, fileName)), LoggingManager.LogType.Info);

            using (var archive = ZipFile.OpenRead(Path.Combine(localPath, fileName)))
            
                ecount = archive.Entries.Count(x => !string.IsNullOrWhiteSpace(x.Name));
                strECount = ecount.ToString();
                lgmr.Log(string.Concat(serviceName, " ", code, ": Files Count: ",ecount, localPath + "\\" + fileName), LoggingManager.LogType.Info);
                foreach (ZipArchiveEntry entry in archive.Entries)
                
                    if (File.Exists(Path.Combine(localPath, entry.Name)))
                    
                         File.Delete(Path.Combine(localPath, entry.Name));
                    
                    entry.ExtractToFile(Path.Combine(localPath, entry.Name));
                
            

            File.Move(Path.Combine(localPath, fileName), Path.Combine(Destinationpath, code + string.Format("Enrollments-0:yyyy-MM-dd_hh-mm-ss.fff.zip", DateTime.Now)));
        
        catch (Exception ex)
        
            //File.Delete(localPath + "\\" + fileName);
            //File.Move(localPath + "\\" + fileName, Destinationpath + "\\" + code + string.Format("ZipErrorEnrollments-0:yyyy-MM-dd_hh-mm-ss.fff.zip", DateTime.Now));
            ecount = 0;               
            lgmr.Log(string.Concat(serviceName, " ", code, " ECount:", ecount, ": Failed to ZIP", localPath + "\\" + fileName, "Resend the Request to WebAPI ", ex.Message), LoggingManager.LogType.Info);
            throw ex;
        
    

【讨论】:

您可能不必重新启动 PC。只需重新启动服务。你能在调试中运行它吗? File.WriteAllBytes(Path.Combine(localPath, fileName), zipByteResponse); // 这里又是异常, 第一次成功运行后,能否检查文件是否真的被移动了。因为你会得到这个错误的唯一原因是文件没有被移动,你尝试创建相同的文件 如何检查文件是否被移动? 重启电脑后,后台服务正常。第二次起同样的例外。文件夹内没有“.zip”文件

以上是关于访问路径“Enrollments.zip”被拒绝,运行后台服务运行后的主要内容,如果未能解决你的问题,请参考以下文章

“对路径的访问被拒绝.” 是怎么回事

vs2022路径拒绝访问

对路径的访问被拒绝,怎么解决

对路径的访问被拒绝怎么办?

“对路径的访问被拒绝.” 是怎么回事

“对路径的访问被拒绝.” 是怎么回事