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

时间:2018-10-24 06:12:44

标签: c# file service zipfile

重新启动PC后,后台服务可以正常工作。如果我重新安装数据库或对数据库进行了任何更改,则我的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 个答案:

答案 0 :(得分: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;
        }
    }