Beispiel #1
0
        static XDocument LoadExportXml()
        {
            XDocument   doc = null;
            PIMServices ps  = new PIMServices();

            try
            {
                using (SftpClient sftp = ps.CreatePIMSftp())
                {
                    sftp.Connect();

                    var directory = "/" + ps.GetPIMExportDirectory();
                    var allFiles  = sftp.ListDirectory(directory);

                    // Load expected files
                    var filesToSearch = (from file in allFiles
                                         where !String.IsNullOrWhiteSpace(file.Name) &&
                                         file.Name.Contains(ps.GetPIMZipFileName())
                                         orderby file.LastWriteTime ascending
                                         select file).ToList();

                    // Remove old files
                    if (filesToSearch.Count > 1)
                    {
                        for (int i = 0; i < filesToSearch.Count - 1; i++)
                        {
                            var file = filesToSearch[i];
                            sftp.DeleteFile(file.FullName);
                        }
                    }

                    // Parse file (should now be only one file)
                    foreach (var file in filesToSearch)
                    {
                        using (MemoryStream ms = new MemoryStream())
                        {
                            sftp.DownloadFile(file.FullName, ms);
                            ms.Position = 0;

                            Stream unzippedMs;

                            // TODO:  Add zip capability
                            ZipArchive archive = new ZipArchive(ms);
                            foreach (ZipArchiveEntry entry in archive.Entries)
                            {
                                if (entry.FullName.IndexOf(ps.GetPIMExportFileName(), StringComparison.OrdinalIgnoreCase) >= 0)
                                {
                                    unzippedMs = entry.Open(); // .Open will return a stream
                                                               //Process entry data here
                                    doc = XDocument.Load(unzippedMs);
                                }
                            }
                        }
                    }

                    sftp.Disconnect();
                }
            }
            catch (Exception ex)
            {
                LogException(ex);
                Console.WriteLine("Unable to load file");
            }

            return(doc);
        }