コード例 #1
0
        private void SaveGeneratedResources(ZipArchive archive, IReadOnlyList <GeneratedResourceSource> generatedResources, IDictionary <Type, string> typeAliases)
        {
            var saveLoadInfos = new List <GeneratedResourceSaveLoadInfo>();

            var zipFileSystem = new ZipFileSystem(archive);

            for (var i = 0; i < generatedResources.Count; i++)
            {
                var source     = generatedResources[i];
                var resource   = source.Resource;
                var folderName = "r" + i;
                var fileName   = resourceSavingService.SuggestFileName(resource, folderName);
                var path       = $"GeneratedResources/{folderName}/{fileName}";
                saveLoadInfos.Add(new GeneratedResourceSaveLoadInfo(source.SaveLoadResourceType, path));
                resourceSavingService.SaveResource(resource, zipFileSystem, path);
            }

            var generatedResourceInfoEntry = archive.CreateEntry("generatedResourceInfos.json");

            using (var writer = trwFactory.JsonWriter(generatedResourceInfoEntry.Open()))
                using (var context = saveLoadFactory.GeneratedResourceInfoWriteContext(writer))
                {
                    context.TypeAliases = typeAliases;
                    context.Write(saveLoadInfos.ToArray());
                }
        }
コード例 #2
0
        public static NuGetDependencyInfo GetDependencyInfo(FileInfo nupkgPath)
        {
            if (!nupkgPath.Exists)
            {
                throw new FileNotFoundException(nupkgPath.FullName);
            }

            using (var stream = nupkgPath.OpenRead())
            {
                ZipFileSystem zip = new ZipFileSystem(stream);

                using (PackageReader packageReader = new PackageReader(zip))
                {
                    using (var nuspecStream = packageReader.GetNuspec())
                    {
                        NuspecReader reader = new NuspecReader(nuspecStream);

                        NuGetPackageId package = CreateIdentity(reader, nupkgPath.FullName);

                        List <NuGetDependencyGroup> dependencyGroups = new List <NuGetDependencyGroup>();

                        foreach (var depGroup in reader.GetDependencyGroups())
                        {
                            FrameworkName framework = Utilities.GetFrameworkName(depGroup.TargetFramework);

                            NuGetDependency[] dependencies = depGroup.Packages.Select(d => new NuGetDependency(d.Id, VersionRange.Parse(d.VersionRange))).ToArray();

                            dependencyGroups.Add(new NuGetDependencyGroup(framework, dependencies));
                        }

                        return(new NuGetDependencyInfo(package, dependencyGroups));
                    }
                }
            }
        }
コード例 #3
0
        public void TestMethod1()
        {
            var Vfs = new ZipFileSystem(Config.ProjectTestInputPath + @"\TestInputMounted.zip", ZipFileSystem.ZipArchiveMode.Read);

            Assert.AreEqual(
                "text.2",
                Vfs.OpenFile("DirectoryOnMountedFileSystem/2.txt", System.IO.FileMode.Open).ReadAllContentsAsString()
                );

            Assert.AreEqual(
                "FileSystemEntry(FullName=DirectoryOnMountedFileSystem/1.txt, Name=1.txt, Size=6, Type=File)" +
                "FileSystemEntry(FullName=DirectoryOnMountedFileSystem/2.txt, Name=2.txt, Size=6, Type=File)" +
                "FileSystemEntry(FullName=DirectoryOnMountedFileSystem/3.txt, Name=3.txt, Size=6, Type=File)"
                ,
                Vfs.FindFiles("/DirectoryOnMountedFileSystem", "*.txt").ToStringArray("")
                );

            Assert.AreEqual(
                "FileSystemEntry(FullName=CompressedFile.txt, Name=CompressedFile.txt, Size=130, Type=File)" +
                "FileSystemEntry(FullName=DirectoryOnMountedFileSystem, Name=DirectoryOnMountedFileSystem, Size=0, Type=Directory)" +
                "FileSystemEntry(FullName=FileInMountedFileSystem.txt, Name=FileInMountedFileSystem.txt, Size=11, Type=File)"
                ,
                Vfs.FindFiles("/").ToStringArray("")
                );
        }
コード例 #4
0
        public async Task <IActionResult> UploadFile(IFormFile file)
        {
            //exercise for the reader: add handling error
            if (file == null || file.Length == 0)
            {
                return(Content("file not selected"));
            }

            string name = Path.GetFileNameWithoutExtension(file.FileName);
            //exercise for the reader : for tenants ,where to store data to be returned ?
            var fullPathFile = Path.Combine(
                _environment.WebRootPath,
                Path.GetFileName(file.FileName));

            if (System.IO.File.Exists(fullPathFile))
            {
                System.IO.File.Delete(fullPathFile);
            }

            using (var stream = new FileStream(fullPathFile, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }
            var fileSystem = new ZipFileSystem(fullPathFile);
            var extractor  = new WordContractExtractor(fileSystem);

            extractor.Start();
            //exercise for the reader : for tenants ,where to store data to be returned ?
            return(Content("upload success"));
        }
コード例 #5
0
ファイル: ResourceManager.cs プロジェクト: lvyitian1/Alex
        public void LoadBedrockPacks(IProgressReceiver progressReceiver, DirectoryInfo directoryInfo)
        {
            progressReceiver?.UpdateProgress(0, "Loading bedrock .MCPack files...");

            var files = directoryInfo.EnumerateFiles("*.mcpack").ToArray();

            for (var index = 0; index < files.Length; index++)
            {
                var file = files[index];
                progressReceiver?.UpdateProgress(index, files.Length, "Loading bedrock .MCPack files...", file.Name);

                try
                {
                    using (var archive = new ZipFileSystem(file.Open(FileMode.Open, FileAccess.Read), file.Name))
                    {
                        MCPack pack = new MCPack(archive);
                        Packs.Add(pack);
                    }
                }
                catch (Exception ex)
                {
                    Log.Warn(ex, $"Failed to load bedrock .MCPack file: {file.Name}: {ex}");
                }
            }
        }
コード例 #6
0
ファイル: ResourceManager.cs プロジェクト: lvyitian1/Alex
        public bool TryLoadResourcePackInfo(string file, out ResourcePackManifest manifest)
        {
            manifest = default;
            if (!File.Exists(file))
            {
                return(false);
            }

            using (FileStream stream = File.OpenRead(file))
                using (var archive = new ZipFileSystem(stream, Path.GetFileNameWithoutExtension(file)))
                {
                    manifest = ResourcePackLib.ResourcePack.GetManifest(archive);

                    if (manifest != null)
                    {
                        manifest.Name = archive.Name;
                    }
                }

            if (manifest == null)
            {
                return(false);
            }

            return(true);
        }
コード例 #7
0
        public IFileSystem ReadDisk(WorkspacePath path)
        {
            IFileSystem disk = null;

            // Found disk to load
            if (path.IsDirectory)
            {
                disk = new SubFileSystem(this, path);
            }
            else if (path.IsFile)
            {
                if (archiveExtensions.IndexOf(path.Path.Split('.').Last()) > -1)
                {
                    using (var stream = ZipFileSystem.Open(OpenFile(path, FileAccess.Read) as FileStream))
                    {
                        disk = stream;

                        // TODO need to see how we can close the stream?
//                        stream.Close();
                    }
                }
            }

            return(disk);
        }
コード例 #8
0
        public void Test_Create_PasswordProtected_ZipFileSystem_And_Write_Files()
        {
            using (var fileSystem = ZipFileSystem.CreateZipFile(FileSystemManager.Default.ResolveFile("temp:///TestZipFile2.zip"), this.WorkingDirectory.ResolveDirectory("Directory1"), FileSystemOptions.Default.AddVariables(new { ZipPassword = "******" })))
            {
                var fileContents = fileSystem.ResolveFile("SubDirectory1/A.csv").GetContent().GetReader().ReadToEnd();

                Assert.AreEqual("A.csv", fileContents);

                var newFile = fileSystem.ResolveFile("SubDirectory1/B.txt");

                newFile.ParentDirectory.Create();

                Assert.IsFalse(newFile.Exists);

                using (var writer = newFile.GetContent().GetWriter(Encoding.UTF8))
                {
                    writer.Write("B.txt");
                }

                Assert.IsTrue(newFile.Exists);
            }

            var fileContents2 = FileSystemManager.Default.ResolveFile("zip://[temp:///TestZipFile2.zip?ZipPassword=pass123]/SubDirectory1/A.csv").GetContent().GetReader().ReadToEnd();

            Console.WriteLine(fileContents2);

            FileSystemManager.Default.ResolveFileSystem("zip://[temp:///TestZipFile2.zip?ZipPassword=pass123]").Close();

            var fileContents3 = new ZipFileSystem(FileSystemManager.Default
                                                  .ResolveFile("temp:///TestZipFile2.zip"), FileSystemOptions.Default.AddVariables(new { ZipPassword = "******" }))
                                .ResolveFile("SubDirectory1/A.csv")
                                .GetContent().GetReader().ReadToEnd();

            Console.WriteLine(fileContents3);
        }
コード例 #9
0
        public Modpack(string path, IFileSystem fileSystem)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentNullException(nameof(path));
            }

            string directory;

            if (fileSystem.DirectoryExists(path))
            {
                directory = path;
                LoadFromFileSystem(fileSystem, directory);
            }
            else if (fileSystem.FileExists(path))
            {
                directory = Path.GetDirectoryName(path);
                var extension = Path.GetExtension(path);
                if (string.Equals(extension, ".zip", StringComparison.OrdinalIgnoreCase))
                {
                    zipStream  = fileSystem.OpenFileReadOnly(path);
                    zipArchive = new ZipArchive(zipStream);

                    var zipFileSystem = new ZipFileSystem(zipArchive);
                    LoadFromFileSystem(zipFileSystem, "/");
                }
                else if (string.Equals(extension, ".csx", StringComparison.OrdinalIgnoreCase) ||
                         string.Equals(extension, ".lua", StringComparison.OrdinalIgnoreCase))
                {
                    metadata = new ModpackMetadata
                    {
                        Name        = Path.GetFileName(path),
                        Description = null,
                        Mods        = new List <ModMetadata>
                        {
                            new ModMetadata
                            {
                                Name        = Path.GetFileName(path),
                                Description = null,
                                Enabled     = true,
                                Scripts     = new List <string>
                                {
                                    Infrastructure.FileSystemExtensions.GetRelativePath(directory, path)
                                }
                            }
                        }
                    };
                    mods = metadata.Mods.Select(m => new Mod(m, directory, fileSystem)).ToList();
                }
                else
                {
                    throw new ArgumentException("Unsupported file extension: " + extension, nameof(path));
                }
            }
            else
            {
                throw new DirectoryNotFoundException("Unable to find either a file or a directory at the given path: " + path);
            }
        }
コード例 #10
0
        public string[] LoadGame(string path)
        {
            var filePath = WorkspacePath.Parse(path);
            var exits    = Exists(filePath);

            string[] files = null;

            if (exits)
            {
                // Found disk to load
                if (filePath.IsDirectory)
                {
                    currentDisk = new SubFileSystem(this, filePath);
                }
                else if (filePath.IsFile)
                {
                    // TODO need to figure out how to do this from a disk now without the currentDisk drive?
                    if (archiveExtensions.IndexOf(filePath.Path.Split('.').Last()) > -1)
                    {
                        using (var stream = OpenFile(filePath, FileAccess.ReadWrite))
                        {
                            if (stream is FileStream)
                            {
                                currentDisk = ZipFileSystem.Open((FileStream)stream);
                            }
                            else
                            {
                                currentDisk = ZipFileSystem.Open(stream, path);
                            }

                            stream.Close();
                        }
                    }
                }

                // We need to get a list of the current mounts

                if (Mounts is SortedList <WorkspacePath, IFileSystem> mounts)
                {
                    // Create a new mount point for the current game
                    var rootPath = WorkspacePath.Root.AppendDirectory("Game");

                    // Make sure we don't have a disk with the same name
                    if (mounts.ContainsKey(rootPath))
                    {
                        mounts.Remove(rootPath);
                    }

                    mounts.Add(rootPath, currentDisk);

                    // Filter out only the files we can use and convert this into a dictionary with the file name as the key and the path as the value
                    files = GetGameEntities(rootPath);
                }
            }

            return(files);
        }
コード例 #11
0
        /// <inheritdoc />
        internal override bool Load()
        {
            try
            {
                List <LoadedSkin> skins = new List <LoadedSkin>();

                using (var archive = new ZipFileSystem(Entry.Open(), Entry.Name))
                {
                    var skinsEntry = archive.GetEntry("skins.json");
                    Info = MCJsonConvert.DeserializeObject <MCPackSkins>(skinsEntry.ReadAsString());

                    var geometryEntry = archive.GetEntry("geometry.json");

                    Dictionary <string, EntityModel> models =
                        MCJsonConvert.DeserializeObject <Dictionary <string, EntityModel> >(geometryEntry.ReadAsString());

                    foreach (var skin in Info.Skins)
                    {
                        EntityModel model;

                        if (!models.TryGetValue(skin.Geometry, out model))
                        {
                            continue;
                        }

                        var textureEntry = archive.GetEntry(skin.Texture);

                        if (textureEntry == null)
                        {
                            continue;
                        }

                        Image <Rgba32> img;

                        using (var s = textureEntry.Open())
                        {
                            //img = new Bitmap(s);
                            img = Image.Load <Rgba32>(s.ReadToSpan(textureEntry.Length), PngDecoder);
                        }

                        LoadedSkin loaded = new LoadedSkin(skin.LocalizationName, model, img);
                        skins.Add(loaded);
                        //skin.
                    }
                }

                Skins = skins.ToArray();

                return(true);
            }
            catch (InvalidDataException ex)
            {
                Log.Debug(ex, $"Could not load module.");
            }

            return(false);
        }
コード例 #12
0
        public override void CalculateSteps()
        {
            base.CalculateSteps();

            if (workspaceService.Exists(diskPath))
            {
                zipFileSystem = workspaceService.Get(diskPath).Value as ZipFileSystem;

                if (zipFileSystem == null || zipFileSystem.PhysicalRoot == null)
                {
                    return;
                }

                // Get the physical path
                physicalPath       = zipFileSystem.PhysicalRoot;
                physicalBackupPath = zipFileSystem.PhysicalRoot + ".bak";

                steps.Add(BackupZip);

                // Get all the files
                var srcFiles = zipFileSystem.GetEntitiesRecursive(WorkspacePath.Root).ToArray();

                // Convert files into the correct format: src/dest path
                var files = new Dictionary <WorkspacePath, WorkspacePath>();
                foreach (var file in srcFiles)
                {
                    files.Add(diskPath.AppendPath(file), file);
                }

                // Create the  zip exporter
                zipExporter = new ZipExporter(diskPath.Path, FileLoadHelper, files);

                // Calculate all the zip steps
                zipExporter.CalculateSteps();

                for (int i = 0; i < zipExporter.totalSteps; i++)
                {
                    steps.Add(NextZipStep);
                }

                // Save the disk
                steps.Add(SaveDisk);

                steps.Add(CheckForErrors);

                steps.Add(Cleanup);
            }
        }
コード例 #13
0
        public IFileSystem GetFileSystem(string bundleName)
        {
            if (_closed)
            {
                return(null);
            }

            IFileSystem   fileSystem = null;
            WeakReference fileSystemRef;

            if (_fileSystems.TryGetValue(bundleName, out fileSystemRef))
            {
                fileSystem = fileSystemRef.Target as IFileSystem;
                if (fileSystem != null)
                {
                    return(fileSystem);
                }
            }

            var bundle = this.GetBundle(bundleName);

            if (bundle != null)
            {
                bundle.AddRef();
                var zipArchiveBundle = bundle as UZipArchiveBundle;
                if (zipArchiveBundle != null)
                {
                    fileSystem = new ZipFileSystem(zipArchiveBundle);
                    _fileSystems[bundleName] = new WeakReference(fileSystem);
                }
                else
                {
                    Debug.LogError($"bundle {bundleName} ({bundle.GetType()}) type error.");
                }

                bundle.RemoveRef();
                if (fileSystem != null)
                {
                    return(fileSystem);
                }
            }

            var invalid = new FailureFileSystem(bundleName);

            _fileSystems[bundleName] = new WeakReference(invalid);
            return(invalid);
        }
コード例 #14
0
        public string MountDisk(string path)
        {
            IFileSystem disk;

            string entityName;

            var attr = File.GetAttributes(path);

            if (attr.HasFlag(FileAttributes.Directory))
            {
                entityName = new DirectoryInfo(path).Name;
            }
            else
            {
                entityName = Path.GetFileNameWithoutExtension(path);
            }

            if (path.EndsWith(".pv8") || path.EndsWith(".zip"))
            {
                disk = ZipFileSystem.Open(path);
            }
            else
            {
                disk = new PhysicalFileSystem(path);
            }

            if (disk == null)
            {
                return(null);
            }

            // Test to see if the disk is a valid game
            if (ValidateGameInDir(disk) == false &&
                disk.Exists(WorkspacePath.Root.AppendFile("info.json")) == false)
            {
                return(null);
            }

            // Update the root path to just be the name of the entity
            var rootPath = WorkspacePath.Root.AppendDirectory("Disks").AppendDirectory(entityName);

            // Add the new disk
            AddDisk(rootPath, disk);

            // Return the disk name
            return(entityName);
        }
コード例 #15
0
        private IDictionary <string, IAsset> LoadAssets(ZipArchive archive, SaveLoadMetadata metadata, IReadOnlyDictionary <string, Type> typeAliases, IFileLoadInfo loadInfo)
        {
            AssetSaveLoadInfo[] assetInfos;
            var assetInfoEntry = archive.GetEntry("assetInfos.json") ?? throw new Exception("assetInfo.json not found.");

            using (var reader = trwFactory.JsonReader(assetInfoEntry.Open()))
                using (var convertedReader = converterContainer.ConvertAssetInfoReader(reader, metadata.Version, converterContainer.CurrentVersion))
                    using (var context = saveLoadFactory.AssetsInfoReadContext(convertedReader, typeAliases))
                        assetInfos = context.Read <AssetSaveLoadInfo[]>();

            var assets           = new Dictionary <string, IAsset>();
            var zipFileSystem    = new ZipFileSystem(archive);
            var actualFileSystem = new ActualFileSystem();

            foreach (var assetInfo in assetInfos)
            {
                var assetLoadInfo = new AssetLoadInfo
                {
                    AssetName     = assetInfo.AssetName,
                    StorageType   = assetInfo.StorageType,
                    ReferencePath = assetInfo.ReferencePath
                };
                switch (assetInfo.StorageType)
                {
                case AssetStorageType.CopyLocal:
                    assetLoadInfo.FileSystem = zipFileSystem;
                    assetLoadInfo.LoadPath   = assetInfo.LocalCopyPath;
                    break;

                case AssetStorageType.ReferenceOriginal:
                    assetLoadInfo.FileSystem = actualFileSystem;
                    assetLoadInfo.LoadPath   = assetInfo.ReferencePath;
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }
                var asset = loadInfo.OnFoundAsset(assetLoadInfo);
                assets.Add(asset.Name, asset);
            }

            return(assets);
        }
コード例 #16
0
        private IReadOnlyList <IResource> LoadGeneratedResources(ZipArchive archive, SaveLoadMetadata metadata, IReadOnlyDictionary <string, Type> typeAliases)
        {
            GeneratedResourceSaveLoadInfo[] generatedResourceInfos;
            var generatedResourceInfoEntry = archive.GetEntry("generatedResourceInfos.json") ?? throw new Exception("generatedResourceInfos.json not found.");

            using (var reader = trwFactory.JsonReader(generatedResourceInfoEntry.Open()))
                using (var convertedReader = converterContainer.ConvertGeneratedResourceInfoReader(reader, metadata.Version, converterContainer.CurrentVersion))
                    using (var context = saveLoadFactory.GeneratedResourceInfoReadContext(convertedReader, typeAliases))
                        generatedResourceInfos = context.Read <GeneratedResourceSaveLoadInfo[]>();

            var generatedResources = new List <IResource>();
            var zipFileSystem      = new ZipFileSystem(archive);

            foreach (var info in generatedResourceInfos)
            {
                generatedResources.Add(resourceLoadingService.Load(info.Type, zipFileSystem, info.Path).WithSource(x => new GeneratedResourceSource(x, info.Type)));
            }

            return(generatedResources);
        }
コード例 #17
0
ファイル: ResourceManager.cs プロジェクト: CiviledCode/Alex
        public bool TryLoadResourcePackInfo(string file, out ResourcePackManifest manifest)
        {
            manifest = default;
            if (!File.Exists(file))
            {
                return(false);
            }

            ResourcePackLib.ResourcePack info;
            using (FileStream stream = File.OpenRead(file))
                using (var archive = new ZipFileSystem(stream))
                    info = ResourcePackLib.ResourcePack.LoadFromArchive(archive);

            if (info == null || info == default)
            {
                return(false);
            }

            manifest = info.Info;
            return(true);
        }
コード例 #18
0
        public void Test_Create_ZipFileSystem_And_Write_Files()
        {
            using (var fileSystem = ZipFileSystem.CreateZipFile(FileSystemManager.Default.ResolveFile("temp:///TestZipFile.zip"), this.WorkingDirectory.ResolveDirectory("Directory1")))
            {
                var fileContents = fileSystem.ResolveFile("SubDirectory1/A.csv").GetContent().GetReader().ReadToEnd();

                Assert.AreEqual("A.csv", fileContents);

                var newFile = fileSystem.ResolveFile("SubDirectory1/B.txt");

                newFile.ParentDirectory.Create();

                Assert.IsFalse(newFile.Exists);

                using (var writer = newFile.GetContent().GetWriter(Encoding.UTF8))
                {
                    writer.Write("B.txt");
                }

                Assert.IsTrue(newFile.Exists);
            }
        }
コード例 #19
0
        public static PackageFragmentValidationResult LoadInstallXml(string zipFilename, out XElement installElement)
        {
            installElement = null;

            ZipFileSystem zipFileSystem = null;

            try
            {
                zipFileSystem = new ZipFileSystem(zipFilename);
            }
            catch (Exception ex)
            {
                return(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex));
            }

            string filename = string.Format("~/{0}", PackageSystemSettings.InstallFilename);

            if (zipFileSystem.ContainsFile(filename) == false)
            {
                return(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, string.Format("Installation file '{0}' is missing from the zip file", filename)));
            }

            try
            {
                using (var stream = zipFileSystem.GetFileStream(filename))
                    using (var streamReader = new C1StreamReader(stream))
                    {
                        string fileContent = streamReader.ReadToEnd();
                        installElement = XElement.Parse(fileContent);
                    }
            }
            catch (Exception ex)
            {
                return(new PackageFragmentValidationResult(PackageFragmentValidationResultType.Fatal, ex));
            }

            return(null);
        }
コード例 #20
0
 public void Test_Walk_Zip_Directory()
 {
     using (var zfs = new ZipFileSystem(this.WorkingDirectory.ResolveFile("TestWalkZipDir.zip")))
     {
         const int limit   = 100;
         int       count   = 0;
         var       entries = new List <INode>();
         foreach (var entry in zfs.RootDirectory.Walk())
         {
             entries.Add(entry);
             if (++count > limit)
             {
                 Assert.Fail("Infinite loop when walking zip directory");
             }
         }
         Assert.AreEqual(5, entries.Count);
         Assert.AreEqual(1, entries.Count(x =>
                                          x.Name == "sample" &&
                                          x.Address.AbsolutePath == "/sample" &&
                                          x.NodeType == NodeType.Directory));
         Assert.AreEqual(1, entries.Count(x =>
                                          x.Name == "TextFile2.txt" &&
                                          x.Address.AbsolutePath == "/sample/TextFile2.txt" &&
                                          x.NodeType == NodeType.File));
         Assert.AreEqual(1, entries.Count(x =>
                                          x.Name == "data" &&
                                          x.Address.AbsolutePath == "/sample/data" &&
                                          x.NodeType == NodeType.Directory));
         Assert.AreEqual(1, entries.Count(x =>
                                          x.Name == "DataFile1.xml" &&
                                          x.Address.AbsolutePath == "/sample/data/DataFile1.xml" &&
                                          x.NodeType == NodeType.File));
         Assert.AreEqual(1, entries.Count(x =>
                                          x.Name == "TextFile1.txt" &&
                                          x.Address.AbsolutePath == "/sample/data/TextFile1.txt" &&
                                          x.NodeType == NodeType.File));
     }
 }
コード例 #21
0
        public void Test_Create_Zip_FileSystem()
        {
            using (var fileSystem = ZipFileSystem.CreateZipFile(FileSystemManager.Default.ResolveFile("temp:///TestZipFile.zip"), this.WorkingDirectory.ResolveDirectory("Directory1")))
            {
                var names = fileSystem.RootDirectory.GetChildNames().ToList();

                Assert.AreEqual(4, names.Count);
                Assert.AreEqual(2, fileSystem.RootDirectory.GetChildren(NodeType.File).Count());
                Assert.AreEqual(2, fileSystem.RootDirectory.GetChildren(NodeType.Directory).Count());

                var dir = fileSystem.ResolveDirectory("SubDirectory1");
                Assert.IsTrue(dir.Exists);

                dir = fileSystem.ResolveDirectory("SubDirectory2");
                Assert.IsTrue(dir.Exists);

                dir = fileSystem.ResolveDirectory("SubDirectory3");
                Assert.IsFalse(dir.Exists);

                Assert.AreEqual("zip://[temp:///TestZipFile.zip]/", fileSystem.RootDirectory.Address.ToString());
                var fileContents = fileSystem.ResolveFile("SubDirectory1/A.csv").GetContent().GetReader().ReadToEnd();

                Assert.AreEqual("A.csv", fileContents);
            }

            using (var fileSystem = FileSystemManager.Default.ResolveDirectory("zip://[temp:///TestZipFile.zip]/").FileSystem)
            {
                var file = fileSystem.ResolveFile("SubDirectory1/A.csv");

                Assert.AreEqual(typeof(ZipFile), file.GetType());

                var fileContents = fileSystem.ResolveFile("SubDirectory1/A.csv").GetContent().GetReader().ReadToEnd();

                Assert.AreEqual("A.csv", fileContents);
            }
        }
コード例 #22
0
        static void Main(string[] args)
        {
            try
            {
                foreach (var path in Directory.EnumerateDirectories("."))
                {
                    CleanDirectory(path);
                    ProcessProfiles(DiskFileSystem.Folder(path), Path.Combine(path, "profiles.json"));
                }

                foreach (var zip in Directory.EnumerateFiles(".", "*.zip"))
                {
                    ProcessProfiles(ZipFileSystem.Open(zip), Path.ChangeExtension(zip, "json"));
                }
                ProcessProfiles(DiskFileSystem.Folder(PortableFrameworkProfileEnumerator.MachineProfilePath), "profiles.json");

                Console.WriteLine("Done.");
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine(ex);
            }
            Console.ReadKey();
        }
コード例 #23
0
ファイル: PackageInstaller.cs プロジェクト: jim116801/C1-CMS
        private IEnumerable <PackageFragmentValidationResult> LoadPackageFragmentInstallerBinaries(XElement packageFragmentInstallerBinariesElement)
        {
            var binaryElements = packageFragmentInstallerBinariesElement.Elements(XmlUtils.GetXName(PackageSystemSettings.XmlNamespace,
                                                                                                    PackageSystemSettings.PackageFragmentInstallerBinariesAddElementName)).ToList();

            if (!binaryElements.Any())
            {
                return(new PackageFragmentValidationResult[0]);
            }

            string binariesDirectory = Path.Combine(this.PackageInstallDirectory, PackageSystemSettings.BinariesDirectoryName);

            if (!C1Directory.Exists(binariesDirectory))
            {
                C1Directory.CreateDirectory(binariesDirectory);
            }

            var result = new List <PackageFragmentValidationResult>();

            foreach (XElement element in binaryElements)
            {
                XAttribute pathAttribute = element.Attribute(PackageSystemSettings.PathAttributeName);

                string sourceFilename = pathAttribute.Value;
                string targetFilename = Path.Combine(binariesDirectory, Path.GetFileName(sourceFilename));

                ZipFileSystem zipFileSystem = new ZipFileSystem(this.ZipFilename);
                if (!zipFileSystem.ContainsFile(sourceFilename))
                {
                    result.AddFatal($"The file '{sourceFilename}' is missing from the zip file");
                    continue;
                }

                // Extracting dll to package temp folder
                if (C1File.Exists(targetFilename))
                {
                    bool success = false;
                    try
                    {
                        FileUtils.Delete(targetFilename);
                        success = true;
                    }
                    catch (UnauthorizedAccessException) {}

                    if (!success)
                    {
                        result.AddFatal($"Access denied to file '{targetFilename}'");
                        continue;
                    }
                }

                zipFileSystem.WriteFileToDisk(sourceFilename, targetFilename);

                string newTargetFilename = Path.Combine(this.TempDirectory, Path.GetFileName(targetFilename));
                C1File.Copy(targetFilename, newTargetFilename);

                Log.LogVerbose("PackageInstaller", "Loading package uninstaller fragment assembly '{0}'", newTargetFilename);

                PackageAssemblyHandler.AddAssembly(newTargetFilename);
            }

            return(result);
        }
コード例 #24
0
ファイル: ResourceManager.cs プロジェクト: CiviledCode/Alex
        private void LoadResourcePacks(GraphicsDevice device, IProgressReceiver progress, string[] resourcePacks)
        {
            var countBefore = ActiveResourcePacks.Count;

            var first = ActiveResourcePacks.First.Value;

            ActiveResourcePacks.Clear();

            ActiveResourcePacks.AddFirst(first);

            if (_hasInit)
            {
                PreloadCallback?.Invoke(first.FontBitmap, McResourcePack.BitmapFontCharacters.ToList());
                Atlas.Reset();
            }

            foreach (string file in resourcePacks)
            {
                try
                {
                    string resourcePackPath = Path.Combine(ResourcePackDirectory.FullName, file);
                    if (File.Exists(resourcePackPath))
                    {
                        Log.Info($"Loading resourcepack {file}...");

                        using (FileStream stream = new FileStream(resourcePackPath, FileMode.Open))
                        {
                            using (ZipFileSystem zipFileSystem = new ZipFileSystem(stream))
                            {
                                var pack = LoadResourcePack(progress, zipFileSystem, null);

                                if (pack.Manifest != null && string.IsNullOrWhiteSpace(pack.Manifest.Name))
                                {
                                    pack.Manifest.Name = Path.GetFileNameWithoutExtension(file);
                                }

                                ActiveResourcePacks.AddLast(pack);
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Log.Warn(e, $"Could not load resourcepack {file}: {e.ToString()}");
                }
            }

            bool isFirst = true;

            isFirst = true;
            foreach (var resourcePack in ActiveResourcePacks)
            {
                LoadModels(progress, resourcePack, !isFirst, isFirst);
                if (isFirst)
                {         //Only load models for vanilla until above we fix blockstate replacement issues.
                    isFirst = false;
                    break;
                }
            }

            isFirst = true;
            foreach (var resourcePack in ActiveResourcePacks)
            {
                Alex.GuiRenderer.LoadLanguages(resourcePack, progress);

                LoadTextures(device, progress, resourcePack, isFirst);

                if (isFirst)
                {
                    isFirst = false;
                }
            }

            progress?.UpdateProgress(50, "Loading language...");
            if (!Alex.GuiRenderer.SetLanguage(Options.AlexOptions.MiscelaneousOptions.Language.Value))
            {
                Alex.GuiRenderer.SetLanguage(CultureInfo.InstalledUICulture.Name);
            }

            progress?.UpdateProgress(100, "Loading language...");

            var f = ActiveResourcePacks.LastOrDefault(x => x.FontBitmap != null);

            if (f != null)
            {
                PreloadCallback?.Invoke(f.FontBitmap, McResourcePack.BitmapFontCharacters.ToList());
            }
        }
コード例 #25
0
        public GameWorld(GameWorldConfiguration configuration,
                         FileSystemPath worldFilePath, TrippingCubesGame game)
        {
            DateTime startTime = DateTime.Now;

            Game = game;

            Entities = new ReadOnlyCollection <IEntity>(entities);

            Physics = new PhysicsSystem(IsBlockSolid, IsBlockLiquid);

            Paths = new ReadOnlyDictionary <string, PathLinear>(
                configuration.Paths ?? new Dictionary <string, PathLinear>());

            Log.Trace("Initializing world style...");
            try
            {
                Game.Resources.LoadMesh(MeshData.Skybox).Subscribe(
                    r => skyboxMesh = r);
                Game.Resources.LoadTexture(configuration.SkyboxPath,
                                           TextureFilter.Linear).Subscribe(
                    r => skyboxTexture = r);
                if (!configuration.InnerSkyboxPath.IsEmpty)
                {
                    Game.Resources.LoadTexture(configuration.InnerSkyboxPath,
                                               TextureFilter.Linear).Subscribe(
                        r => innerSkyboxTexture = r);
                }
            }
            catch (Exception exc)
            {
                Log.Warning("The skybox couldn't be loaded and will not " +
                            "be available.", exc);
            }
            try
            {
                DateTime             localStartTime       = DateTime.Now;
                BlockRegistryBuilder blockRegistryBuilder =
                    BlockRegistryBuilder.FromXml(
                        configuration.BlockRegistryPath,
                        FileSystem, false);
                Blocks = blockRegistryBuilder.GenerateRegistry(
                    FileSystem);
                Log.Trace("Block registry with " + Blocks.Count +
                          " block definitions initialized in " +
                          (DateTime.Now - localStartTime).TotalMilliseconds + "ms.");
            }
            catch (Exception exc)
            {
                throw new Exception("The block registry couldn't be " +
                                    "initialized.", exc);
            }


            Log.Trace("Initializing world chunk manager...");
            try
            {
                FileSystemPath primaryWorldBackupPath =
                    FileSystemPath.Combine(worldFilePath.GetParentDirectory(),
                                           $"{worldFilePath.GetFileName(false)}1");
                FileSystemPath secondaryWorldBackupPath =
                    FileSystemPath.Combine(worldFilePath.GetParentDirectory(),
                                           $"{worldFilePath.GetFileName(false)}2");

                if (FileSystem.IsWritable)
                {
                    try
                    {
                        if (FileSystem.ExistsFile(primaryWorldBackupPath))
                        {
                            using Stream secondaryBackupStream =
                                      FileSystem.CreateFile(secondaryWorldBackupPath,
                                                            true);
                            using Stream primaryWorldBackup =
                                      FileSystem.OpenFile(primaryWorldBackupPath,
                                                          false);

                            primaryWorldBackup.CopyTo(secondaryBackupStream);
                        }

                        if (FileSystem.ExistsFile(worldFilePath))
                        {
                            using Stream primaryWorldBackup =
                                      FileSystem.CreateFile(primaryWorldBackupPath,
                                                            true);
                            using Stream worldFile =
                                      FileSystem.OpenFile(worldFilePath, false);

                            worldFile.CopyTo(primaryWorldBackup);
                        }
                    }
                    catch (Exception exc)
                    {
                        throw new Exception("The world backups couldn't be " +
                                            "updated.", exc);
                    }
                }

                if (FileSystem.ExistsFile(worldFilePath))
                {
                    zipFileSystem = new ZipFileSystem(FileSystem.OpenFile(
                                                          worldFilePath, FileSystem.IsWritable));
                }
                else if (FileSystem.IsWritable)
                {
                    Log.Information("No world data file was found at the " +
                                    "specified path. A new world file is initialized.");
                    zipFileSystem = ZipFileSystem.Initialize(FileSystem,
                                                             worldFilePath, false);
                }
                else
                {
                    throw new Exception("The world data file doesn't exist " +
                                        $"under the path {worldFilePath} and can't be created, " +
                                        "as the file system is read-only.");
                }

                RootChunk = new Chunk <BlockVoxel>(
                    new BlockChunkManager(Blocks, Game.Resources,
                                          zipFileSystem, "/"));
            }
            catch (Exception exc)
            {
                throw new Exception("The world chunk manager couldn't be " +
                                    "initialized.", exc);
            }


            Log.Trace("Spawning entities...");
            foreach (EntityInstantiation instantiation in
                     configuration.Entities)
            {
                if (configuration.EntityConfigurations.TryGetValue(
                        instantiation.ConfigurationIdentifier,
                        out EntityConfiguration entityConfiguration))
                {
                    try
                    {
                        IEntity entity = entityConfiguration.Instantiate(this,
                                                                         instantiation.InstanceParameters);
                        entities.Add(entity);
                    }
                    catch (Exception exc)
                    {
                        Log.Warning($"Entity #{entities.Count} couldn't " +
                                    "be spawned and will be skipped.", exc);
                    }
                }
            }
            Log.Trace($"Spawned {entities.Count} entities.");

            Log.Trace("Game world initialized in " +
                      (DateTime.Now - startTime).TotalMilliseconds + "ms.");
        }
コード例 #26
0
        /// <summary>
        /// Returns artifact info for packages in a packages.config that match the given set of properties.
        /// </summary>
        /// <param name="configPath">Path to packages.config</param>
        /// <param name="properties">Property values to filter on</param>
        /// <returns>Artifacts matching the property filters.</returns>
        public static IEnumerable <NuGetArtifactInfo> GetArtifactInfo(string configPath, IEnumerable <string> propertyKeys)
        {
            if (configPath == null)
            {
                throw new ArgumentNullException("configPath");
            }

            if (propertyKeys == null)
            {
                throw new ArgumentNullException("propertyKeys");
            }

            FileInfo file = new FileInfo(configPath);

            if (!file.Exists)
            {
                throw new FileNotFoundException(configPath);
            }

            List <NuGetArtifactInfo> results = new List <NuGetArtifactInfo>();

            using (FileStream stream = file.OpenRead())
            {
                ConfigReader configReader = new ConfigReader(stream);

                foreach (PackageIdentity package in configReader.GetPackages())
                {
                    // TODO: find the real path
                    string   packageName = package.Id + "." + package.Version.ToString();
                    FileInfo nupkgPath   = new FileInfo(Path.Combine(file.Directory.Parent.FullName, "packages", packageName, packageName + ".nupkg"));

                    if (!nupkgPath.Exists)
                    {
                        throw new FileNotFoundException(nupkgPath.FullName);
                    }

                    NuGetPackageId id = new NuGetPackageId(package.Id, package.Version, nupkgPath.Directory.FullName);

                    ZipFileSystem zip = new ZipFileSystem(nupkgPath.OpenRead());

                    using (PackageReader packageReader = new PackageReader(zip))
                    {
                        ComponentTree tree = null;

                        // TODO: add a better check for this
                        if (packageReader.GetPackedManifest() == null)
                        {
                            using (LegacyPackageReader legacyReader = new LegacyPackageReader(zip))
                            {
                                throw new NotImplementedException();
                                //var packed = PackedManifestCreator.FromLegacy(legacyReader);
                                //tree = packed.ComponentTree;
                            }
                        }
                        else
                        {
                            tree = packageReader.GetComponentTree();
                        }

                        List <NuGetArtifactGroup> groups = new List <NuGetArtifactGroup>();

                        // TODO: use propertyKeys
                        // TODO: get full paths
                        foreach (var path in tree.GetPaths())
                        {
                            var props = path.Properties.Select(p => (KeyValueTreeProperty)p).Select(p => new KeyValuePair <string, string>(p.Key, p.Value));
                            var items = path.Items.Select(i => (NuGetTreeItem)i).Select(i => new NuGetArtifact(i.Type, i.Data.Where(p => p.Key == "path").Select(p => p.Value).Single()));

                            groups.Add(new NuGetArtifactGroup(props, items));
                        }

                        NuGetArtifactInfo info = new NuGetArtifactInfo(id, groups.ToArray());
                        results.Add(info);
                    }
                }
            }

            return(results);
        }
コード例 #27
0
        public void Test_Create_Empty_ZipFileSystem_And_Write_Files()
        {
            using (var fileSystem = ZipFileSystem.CreateZipFile(FileSystemManager.Default.ResolveFile("temp:///TestReadWriteZipFile.zip")))
            {
                var newFile = fileSystem.ResolveFile("Test.txt");

                Assert.IsFalse(newFile.Exists);

                using (var writer = newFile.GetContent().GetWriter())
                {
                    writer.Write("Test");
                }

                newFile.Refresh();
                Assert.IsTrue(newFile.Exists);

                var newFile2 = fileSystem.ResolveFile("/TestDir/A.txt");

                Assert.IsFalse(newFile2.ParentDirectory.Exists);
                newFile2.ParentDirectory.Create();
                Assert.IsTrue(newFile2.ParentDirectory.Exists);

                Assert.IsFalse(newFile2.Exists);

                using (var writer = newFile2.GetContent().GetWriter())
                {
                    writer.Write("A");
                }

                newFile2.Refresh();
                Assert.IsTrue(newFile2.Exists);

                fileSystem.ResolveDirectory("/NewDirectory").Create();

                var z = fileSystem.ResolveDirectory("/X/Y/Z");

                Assert.IsFalse(z.Exists);

                Assert.Catch <DirectoryNodeNotFoundException>(() => z.Create());

                z.Create(true);

                Assert.IsTrue(z.Exists);
                Assert.IsTrue(fileSystem.ResolveDirectory("/X/Y").Exists);
                Assert.IsTrue(fileSystem.ResolveDirectory("/X").Exists);
            }

            using (var fileSystem = FileSystemManager.Default.ResolveDirectory("zip://[temp:///TestReadWriteZipFile.zip]/").FileSystem)
            {
                var testFile = fileSystem.ResolveFile("Test.txt");

                Assert.AreEqual("Test", testFile.GetContent().GetReader().ReadToEndThenClose());

                using (var writer = testFile.GetContent().GetWriter())
                {
                    writer.Write("Hello");
                }

                Assert.IsTrue(testFile.Exists);

                Assert.AreEqual("Hello", testFile.GetContent().GetReader().ReadToEndThenClose());

                Assert.IsTrue(fileSystem.ResolveDirectory("/NewDirectory").Exists);
                Assert.IsTrue(fileSystem.ResolveDirectory("/X/Y/Z").Exists);
                Assert.IsTrue(fileSystem.ResolveDirectory("/X/Y").Exists);
                Assert.IsTrue(fileSystem.ResolveDirectory("/X").Exists);
            }

            using (var fileSystem = FileSystemManager.Default.ResolveDirectory("zip://[temp:///TestReadWriteZipFile.zip]/").FileSystem)
            {
                var testFile = fileSystem.ResolveFile("Test.txt");

                Assert.AreEqual("Hello", testFile.GetContent().GetReader().ReadToEndThenClose());

                testFile.Delete();
            }

            using (var fileSystem = FileSystemManager.Default.ResolveDirectory("zip://[temp:///TestReadWriteZipFile.zip]/").FileSystem)
            {
                var testFile = fileSystem.ResolveFile("Test.txt");

                Assert.IsFalse(testFile.Exists);
            }
        }
コード例 #28
0
        /// <summary>
        /// Returns artifact info for packages in a packages.config that match the given set of properties.
        /// </summary>
        /// <param name="configPath">Path to packages.config</param>
        /// <param name="properties">Property values to filter on</param>
        /// <returns>Artifacts matching the property filters.</returns>
        public static IEnumerable<NuGetArtifactInfo> GetArtifactInfo(string configPath, IEnumerable<string> propertyKeys)
        {
            if (configPath == null)
            {
                throw new ArgumentNullException("configPath");
            }

            if (propertyKeys == null)
            {
                throw new ArgumentNullException("propertyKeys");
            }

            FileInfo file = new FileInfo(configPath);

            if (!file.Exists)
            {
                throw new FileNotFoundException(configPath);
            }

            List<NuGetArtifactInfo> results = new List<NuGetArtifactInfo>();

            using (FileStream stream = file.OpenRead())
            {
                ConfigReader configReader = new ConfigReader(stream);

                foreach (PackageIdentity package in configReader.GetPackages())
                {
                    // TODO: find the real path
                    string packageName = package.Id + "." + package.Version.ToString();
                    FileInfo nupkgPath = new FileInfo(Path.Combine(file.Directory.Parent.FullName, "packages",  packageName, packageName + ".nupkg"));

                    if (!nupkgPath.Exists)
                    {
                        throw new FileNotFoundException(nupkgPath.FullName);
                    }

                    NuGetPackageId id = new NuGetPackageId(package.Id, package.Version, nupkgPath.Directory.FullName);

                    ZipFileSystem zip = new ZipFileSystem(nupkgPath.OpenRead());

                    using (PackageReader packageReader = new PackageReader(zip))
                    {
                        ComponentTree tree = null;

                        // TODO: add a better check for this
                        if (packageReader.GetPackedManifest() == null)
                        {
                            using (LegacyPackageReader legacyReader = new LegacyPackageReader(zip))
                            {
                                throw new NotImplementedException();
                                //var packed = PackedManifestCreator.FromLegacy(legacyReader);
                                //tree = packed.ComponentTree;
                            }
                        }
                        else
                        {
                            tree = packageReader.GetComponentTree();
                        }

                        List<NuGetArtifactGroup> groups = new List<NuGetArtifactGroup>();

                        // TODO: use propertyKeys
                        // TODO: get full paths
                        foreach (var path in tree.GetPaths())
                        {
                            var props = path.Properties.Select(p => (KeyValueTreeProperty)p).Select(p => new KeyValuePair<string, string>(p.Key, p.Value));
                            var items = path.Items.Select(i => (NuGetTreeItem)i).Select(i => new NuGetArtifact(i.Type, i.Data.Where(p => p.Key == "path").Select(p => p.Value).Single()));

                            groups.Add(new NuGetArtifactGroup(props, items));
                        }

                        NuGetArtifactInfo info = new NuGetArtifactInfo(id, groups.ToArray());
                        results.Add(info);
                    }
                }
            }

            return results;
        }
コード例 #29
0
        public static NuGetDependencyInfo GetDependencyInfo(FileInfo nupkgPath)
        {
            if (!nupkgPath.Exists)
            {
                throw new FileNotFoundException(nupkgPath.FullName);
            }

            using (var stream =nupkgPath.OpenRead())
            {
                ZipFileSystem zip = new ZipFileSystem(stream);

                using (PackageReader packageReader = new PackageReader(zip))
                {
                    using (var nuspecStream = packageReader.GetNuspec())
                    {
                        NuspecReader reader = new NuspecReader(nuspecStream);

                        NuGetPackageId package = CreateIdentity(reader, nupkgPath.FullName);

                        List<NuGetDependencyGroup> dependencyGroups = new List<NuGetDependencyGroup>();

                        foreach (var depGroup in reader.GetDependencyGroups())
                        {
                            FrameworkName framework = Utilities.GetFrameworkName(depGroup.TargetFramework);

                            NuGetDependency[] dependencies = depGroup.Packages.Select(d => new NuGetDependency(d.Id, VersionRange.Parse(d.VersionRange))).ToArray();

                            dependencyGroups.Add(new NuGetDependencyGroup(framework, dependencies));
                        }

                        return new NuGetDependencyInfo(package, dependencyGroups);
                    }
                }
            }
        }
コード例 #30
0
        public Dictionary <string, byte[]> LoadGame(string path)
        {
            var filePath = WorkspacePath.Parse(path); //FileSystemPath.Root.AppendPath(fullPath);
            var exits    = Exists(filePath);

            Dictionary <string, byte[]> files = null;

            if (exits)
            {
                try
                {
                    // Found disk to load
                    if (filePath.IsDirectory)
                    {
                        currentDisk = new SubFileSystem(this, filePath);
                    }
                    else if (filePath.IsFile)
                    {
                        if (archiveExtensions.IndexOf(filePath.Path.Split('.').Last()) > -1)
                        {
                            using (var stream = OpenFile(filePath, FileAccess.ReadWrite))
                            {
                                if (stream is FileStream)
                                {
                                    currentDisk = ZipFileSystem.Open((FileStream)stream);
                                }
                                else
                                {
                                    currentDisk = ZipFileSystem.Open(stream, path);
                                }

                                stream.Close();
                            }
                        }
                    }

                    // We need to get a list of the current mounts
                    var mounts = Mounts as SortedList <WorkspacePath, IFileSystem>;

                    // Create a new mount point for the current game
                    var rootPath = WorkspacePath.Root.AppendDirectory("Game");

                    // Make sure we don't have a disk with the same name
                    if (mounts.ContainsKey(rootPath))
                    {
                        mounts.Remove(rootPath);
                    }

                    mounts.Add(rootPath, currentDisk);

                    files = ConvertDiskFilesToBytes(currentDisk);

                    IncludeLibDirectoryFiles(files);


                    try
                    {
                        // Convert the path to a system path
                        var tmpFilePath = WorkspacePath.Parse(path);


                        // TODO should we still try to load the saves file from a zip?

                        // If the path is a directory we are going to look for a save file in it
                        if (tmpFilePath.IsDirectory)
                        {
                            tmpFilePath = tmpFilePath.AppendFile("saves.json");

//                        if (WriteAccess(tmpFilePath) == false)
//                        {
                            // Check if save file is in tmp directory
                            var saveFile = WorkspacePath.Parse(FindValidSavePath(tmpFilePath.Path));

                            if (saveFile.Path != "/" && Exists(saveFile))
                            {
                                using (var memoryStream = new MemoryStream())
                                {
                                    using (var file = OpenFile(saveFile, FileAccess.Read))
                                    {
                                        file.CopyTo(memoryStream);
                                        file.Close();
                                    }

                                    var fileName = saveFile.EntityName;
                                    var data     = memoryStream.ToArray();

                                    if (files.ContainsKey(fileName))
                                    {
                                        files[fileName] = data;
                                    }
                                    else
                                    {
                                        files.Add(fileName, data);
                                    }

                                    memoryStream.Close();
                                }
                            }
                        }


//                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }


//                    return true;
                }
                catch
                {
                    //		        // TODO need to have a clearer messgae, like not a mount point or can't load from X because of Y
//                    Console.WriteLine("System Error: Could not load from path " + filePath.Path);
                }
            }

            return(files);
        }