Web Servis ile Zipli Dosya Alma C#

Herhangi web servisten dönen zipli bir dosya olduğunu düşünelim. Zipli dosya içinde ki json uzantılı dosyanın içindeki veriler alınıp sql’de bir tabloya atılacak.

 public static JObject GetCustomersFromApi()
 {  
      HttpResponseMessage result;
           
            var method = "api/GetAllUserListZip";
            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization", token);

                result = client.GetAsync(baseUrl + method).Result;
            }
            string responseBody = result.Content.ReadAsStringAsync().Result;
            JObject jObject = JObject.Parse(responseBody);
            //response içinde müşteri listesi zipli olarak gelmektedir.Bu zip dosyası unzip yapılıp string ifadeye çevrilmektedir.
            string jsonFile = ConvertJsonFileFromAllUserListZipFile(jObject);
            jObject = JObject.Parse(jsonFile);
   }

ConvertJsonFileFromAllUserListZipFile metoduna bakalım :

private static string ConvertJsonFileFromAllUserListZipFile(JObject jObject)
        {
            //json object olarak dönen response içinde data objesinin içindeki UserListFileBytes alınacak
            string UserLİstFile = jObject["CustomerListFileBytes"].ToString();
            // UserListFileBytes byte array'a çevrilecek.
            byte[] byteArray = Convert.FromBase64String(UserLİstFile);
            //zip file unzip yapılıp dosyaya kaydedilecek user list klasörde kayıtlı json uzantılı dosyadan okunacak.
            string zipFile = SaveAllUserListZipFile(byteArray);
            ZipArchive archive = ZipFile.OpenRead(zipFile);
            string jsonFile = "";
            foreach (var entry in archive.Entries)
            {

                using (Stream stream = entry.Open())
                {
                    StreamReader reader = new StreamReader(stream);
                    jsonFile = reader.ReadToEnd();
                }

            }

            return jsonFile;
        }

SaveAllUserListZipFile metoduna bakalım :

public static string SaveAllUserListZipFile(byte[] fileDatas)
        {
            string fileUploadPath = ConfigurationManager.AppSettings("FileUploadPath");
            
// Her defasında unique bir dosya oluşturacak.
            Guid guid = Guid.NewGuid();
            string savingDirectory = Path.Combine(fileUploadPath, "UserListZipFile");
            if (!Directory.Exists(savingDirectory))
                Directory.CreateDirectory(savingDirectory);

            string savingFilePath = Path.Combine(savingDirectory, guid.ToString() + ".zip");
            File.WriteAllBytes(savingFilePath, fileDatas);
            return savingFilePath;
        }

Elimizde jObject formatında veri var. Bu veriyi tabloya aktaralım. Elimizde tablodaki kolanlarla aynı isimde değerlere sahip bir class olsun. Bu class’ın ismi Customer olsun.

public static void GetCustomerList()
{
//yukarıda yazılan metodu kullanıyoruz.
JObject jobject = GetCustomersFromApi();
List<Customer> datas = jobject["Customers"].ToObject<List<Customer>>();
}
//elimizdeki datas objesini kullanarak sql'deki tabloya insert işlemi yapabiliriz.

Yorum bırakın