Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 访问路径';注册。zip';在运行后台服务后被拒绝_C#_File_Service_Zipfile - Fatal编程技术网

C# 访问路径';注册。zip';在运行后台服务后被拒绝

C# 访问路径';注册。zip';在运行后台服务后被拒绝,c#,file,service,zipfile,C#,File,Service,Zipfile,重新启动电脑后,我的后台服务工作正常。如果我重新安装或更改数据库,我的电脑访问路径“.zip”将被拒绝。还有一件事是,同一个背景在另一台电脑上运行 两个后台服务运行在两台不同的PC上,用于交换数据 代码如下: public void GetFilesFromWebAPIAndCountTemplates(DateTime startTime,DateTime endTime,string webAPIURL,string code,string localPath) {

重新启动电脑后,我的后台服务工作正常。如果我重新安装或更改数据库,我的电脑访问路径“.zip”将被拒绝。还有一件事是,同一个背景在另一台电脑上运行

两个后台服务运行在两台不同的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 GetFilesFromWebAPIAndCountTemplates(DateTime startTime、DateTime endTime、string webapirl、string code、string localPath)
{           
ZipLocationsCount zipLocation=null;
计数=0;
如果(开始时间<结束时间)
{
WebApiCall apiCall=新的WebApiCall();
睡眠(10000);
var zipByteResponse=apiCall.CallZipWebApi(webAPIURL,“api/ZIPEnrollmentsDownload/ZIPResponse?startTime=“+startTime+”&endTime=“+endTime+”&locationCode=“+code,null,Constants.Get”);
Log(string.Concat(serviceName,“,code,”:从WebAPI成功获取响应),LoggingManager.LogType.Info);
if(zipbytesponse.Result!=null&&zipbytesponse.Result.Length>0)
{
字符串文件名=代码+“\u Enrollments.zip”;
尝试
{                       
ConvertToziPandMoveToBackup(本地路径、文件名、zipByteResponse.Result、代码);
}
捕获(例外情况除外)
{
//GetFilesFromWebAPIAndCountTemplates(开始时间、结束时间、webAPIURL、代码、本地路径);
ecount=0;
strecont=“无法压缩”;
lgmr.Log(string.Concat(serviceName,“”,代码,“count:”,ecoount,“:未能转换为ZIP”,ex.StackTrace,ex.InnerException,ex.Message),LoggingManager.LogType.Error);
后藤标签1;
}
}
其他的
{
ecount=0;
如果(ecount==0)
{
strecont=“无入学”;
}
lgmr.Log(string.Concat(serviceName,“,code,”:无注册),LoggingManager.LogType.Info);
}
}
其他的
{
lgmr.Log(string.Concat(serviceName,“,code,”:开始日期应小于结束日期),LoggingManager.LogType.Info);
}
fpsynchronistory fpSync=新的fpsynchronistory();
fpSync.LocationCode=代码;
fpSync.FromDate=开始时间;
fpSync.ToDate=结束时间;
fpSync.FPExported=ecoount;
fpSync.Status=true;
fpSync.CreatedBy=1;
fpSync.CreatedOn=DateTime.Now;
fpsynchronistories.Add(fpSync);
标签1:
zipLocation=new ZipLocationsCount(){LocationCode=code,FromDate=startTime,ToDate=endTime,EnrollmentsCount=strECount};
if(zipLocation.FromDate
上面的方法是我调用的另一个方法

 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;
        }
    }
public void GetZipResponseFromWebAPI()
{
尝试
{                
zipLocationsCounts=新列表();
fpsynchronistories=新列表();
DateTime sTime=新的DateTime();
DateTime startTime=new DateTime();
DateTime eTime=newdatetime();
DateTime endTime=新的DateTime();
foreach(FPSyncLocationDetail fpLocation在tmlenty.FPSyncLocationDetails中)
{                   
var findHistory=tmlenty.fpsynchronistories.FirstOrDefault(x=>x.LocationCode==fpLocation.Code);
if(findHistory==null)
{                      
如果(fpLocation.Status==true)
{
sTime=DateTime.Now.AddDays(-1);
startTime=新日期时间(时间年、时间月、时间日,00、00、00);
eTime=DateTime.Now.AddDays(-1);
endTime=新日期时间(eTime.Year,eTime.Month,eTime.Day,23,59,59);
GetFilesFromWebAPIAndCountTemplates(开始时间、结束时间、fpLocation.WebAPIURL、fpLocation.Code、fpLocation.LocalFPFolderPath);
}
}
else if(findHistory!=null)
{
var locationLastDates=从tmlEntity.fpsynchronistories中的n开始
按n分组。位置代码为g
选择新的{LocationCode=g.Key,ToDate=g.Max(t=>t.ToDate)};
foreach(位置LastDates中的var loc)
{
如果(fpLocation.Code==loc.LocationCode)
{
如果(fpLocation.Status==true)
{
时间=loc.ToDate.ADDD天(1);
startTime=新日期时间(时间年、时间月、时间日,00、00、00);
eTime=DateTime.Now.AddDays(-1);
endTime=新日期时间(eTime.Year,eTime.Month,eTime.Day,23,59,59);
GetFilesFromWebAPIAndCountTemplates(开始时间、结束时间、fpLocation.WebAPIURL、fpLocation.Code、fpLocation.LocalFPFolderPath);
}
}
}
}
}                              
}
捕获(例外情况除外)
{
字符串InnerException=ex.InnerException!=null?ex.InnerException.ToString():“”;
lgmr.Log(string.Concat(“GetZipResponseFromWebAPI错误”,ex.StackTrace,ex.InnerException,ex.Message),LoggingManager.LogType.Error);
返回;
}
}
最后在下面调用WebAPI方法逻辑

 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;
        }
    }
公共异步任务调用
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;
        }
    }