├── .gitignore ├── LICENSE ├── README.md ├── VFSTest ├── Data │ ├── Mod1.pak │ │ ├── file1.txt │ │ └── file2.txt │ ├── Mod2.pak │ │ ├── file2.txt │ │ └── folder │ │ │ ├── file3.txt │ │ │ └── subfolder │ │ │ ├── file6.txt │ │ │ └── sub-sub-folder │ │ │ └── file7.txt │ └── Mod3.pak ├── Program.cs └── VFSTest.csproj ├── VirtualFileSystem.sln └── VirtualFileSystem ├── BaseVirtualFile.cs ├── VFSManager.cs ├── VirtualFileSystem.csproj ├── VirtualOSFile.cs └── VirtualZippedFile.cs /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.suo 8 | *.user 9 | *.userosscache 10 | *.sln.docstates 11 | *.editorconfig 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Build results 17 | [Dd]ebug/ 18 | [Dd]ebugPublic/ 19 | [Rr]elease/ 20 | [Rr]eleases/ 21 | x64/ 22 | x86/ 23 | bld/ 24 | [Bb]in/ 25 | [Oo]bj/ 26 | [Ll]og/ 27 | 28 | # Visual Studio 2015/2017 cache/options directory 29 | .vs/ 30 | # Uncomment if you have tasks that create the project's static files in wwwroot 31 | #wwwroot/ 32 | 33 | # Visual Studio 2017 auto generated files 34 | Generated\ Files/ 35 | 36 | # MSTest test Results 37 | [Tt]est[Rr]esult*/ 38 | [Bb]uild[Ll]og.* 39 | 40 | # NUNIT 41 | *.VisualState.xml 42 | TestResult.xml 43 | 44 | # Build Results of an ATL Project 45 | [Dd]ebugPS/ 46 | [Rr]eleasePS/ 47 | dlldata.c 48 | 49 | # Benchmark Results 50 | BenchmarkDotNet.Artifacts/ 51 | 52 | # .NET Core 53 | project.lock.json 54 | project.fragment.lock.json 55 | artifacts/ 56 | 57 | # StyleCop 58 | StyleCopReport.xml 59 | 60 | # Files built by Visual Studio 61 | *_i.c 62 | *_p.c 63 | *_i.h 64 | *.ilk 65 | *.meta 66 | *.obj 67 | *.iobj 68 | *.pch 69 | *.pdb 70 | *.ipdb 71 | *.pgc 72 | *.pgd 73 | *.rsp 74 | *.sbr 75 | *.tlb 76 | *.tli 77 | *.tlh 78 | *.tmp 79 | *.tmp_proj 80 | *.log 81 | *.vspscc 82 | *.vssscc 83 | .builds 84 | *.pidb 85 | *.svclog 86 | *.scc 87 | 88 | # Chutzpah Test files 89 | _Chutzpah* 90 | 91 | # Visual C++ cache files 92 | ipch/ 93 | *.aps 94 | *.ncb 95 | *.opendb 96 | *.opensdf 97 | *.sdf 98 | *.cachefile 99 | *.VC.db 100 | *.VC.VC.opendb 101 | 102 | # Visual Studio profiler 103 | *.psess 104 | *.vsp 105 | *.vspx 106 | *.sap 107 | 108 | # Visual Studio Trace Files 109 | *.e2e 110 | 111 | # TFS 2012 Local Workspace 112 | $tf/ 113 | 114 | # Guidance Automation Toolkit 115 | *.gpState 116 | 117 | # ReSharper is a .NET coding add-in 118 | _ReSharper*/ 119 | *.[Rr]e[Ss]harper 120 | *.DotSettings.user 121 | 122 | # JustCode is a .NET coding add-in 123 | .JustCode 124 | 125 | # TeamCity is a build add-in 126 | _TeamCity* 127 | 128 | # DotCover is a Code Coverage Tool 129 | *.dotCover 130 | 131 | # AxoCover is a Code Coverage Tool 132 | .axoCover/* 133 | !.axoCover/settings.json 134 | 135 | # Visual Studio code coverage results 136 | *.coverage 137 | *.coveragexml 138 | 139 | # NCrunch 140 | _NCrunch_* 141 | .*crunch*.local.xml 142 | nCrunchTemp_* 143 | 144 | # MightyMoose 145 | *.mm.* 146 | AutoTest.Net/ 147 | 148 | # Web workbench (sass) 149 | .sass-cache/ 150 | 151 | # Installshield output folder 152 | [Ee]xpress/ 153 | 154 | # DocProject is a documentation generator add-in 155 | DocProject/buildhelp/ 156 | DocProject/Help/*.HxT 157 | DocProject/Help/*.HxC 158 | DocProject/Help/*.hhc 159 | DocProject/Help/*.hhk 160 | DocProject/Help/*.hhp 161 | DocProject/Help/Html2 162 | DocProject/Help/html 163 | 164 | # Click-Once directory 165 | publish/ 166 | 167 | # Publish Web Output 168 | *.[Pp]ublish.xml 169 | *.azurePubxml 170 | # Note: Comment the next line if you want to checkin your web deploy settings, 171 | # but database connection strings (with potential passwords) will be unencrypted 172 | *.pubxml 173 | *.publishproj 174 | 175 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 176 | # checkin your Azure Web App publish settings, but sensitive information contained 177 | # in these scripts will be unencrypted 178 | PublishScripts/ 179 | 180 | # NuGet Packages 181 | *.nupkg 182 | # The packages folder can be ignored because of Package Restore 183 | **/[Pp]ackages/* 184 | # except build/, which is used as an MSBuild target. 185 | !**/[Pp]ackages/build/ 186 | # Uncomment if necessary however generally it will be regenerated when needed 187 | #!**/[Pp]ackages/repositories.config 188 | # NuGet v3's project.json files produces more ignorable files 189 | *.nuget.props 190 | *.nuget.targets 191 | 192 | # Microsoft Azure Build Output 193 | csx/ 194 | *.build.csdef 195 | 196 | # Microsoft Azure Emulator 197 | ecf/ 198 | rcf/ 199 | 200 | # Windows Store app package directories and files 201 | AppPackages/ 202 | BundleArtifacts/ 203 | Package.StoreAssociation.xml 204 | _pkginfo.txt 205 | *.appx 206 | 207 | # Visual Studio cache files 208 | # files ending in .cache can be ignored 209 | *.[Cc]ache 210 | # but keep track of directories ending in .cache 211 | !*.[Cc]ache/ 212 | 213 | # Others 214 | ClientBin/ 215 | ~$* 216 | *~ 217 | *.dbmdl 218 | *.dbproj.schemaview 219 | *.jfm 220 | *.pfx 221 | *.publishsettings 222 | orleans.codegen.cs 223 | 224 | # Including strong name files can present a security risk 225 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 226 | #*.snk 227 | 228 | # Since there are multiple workflows, uncomment next line to ignore bower_components 229 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 230 | #bower_components/ 231 | 232 | # RIA/Silverlight projects 233 | Generated_Code/ 234 | 235 | # Backup & report files from converting an old project file 236 | # to a newer Visual Studio version. Backup files are not needed, 237 | # because we have git ;-) 238 | _UpgradeReport_Files/ 239 | Backup*/ 240 | UpgradeLog*.XML 241 | UpgradeLog*.htm 242 | ServiceFabricBackup/ 243 | *.rptproj.bak 244 | 245 | # SQL Server files 246 | *.mdf 247 | *.ldf 248 | *.ndf 249 | 250 | # Business Intelligence projects 251 | *.rdl.data 252 | *.bim.layout 253 | *.bim_*.settings 254 | *.rptproj.rsuser 255 | 256 | # Microsoft Fakes 257 | FakesAssemblies/ 258 | 259 | # GhostDoc plugin setting file 260 | *.GhostDoc.xml 261 | 262 | # Node.js Tools for Visual Studio 263 | .ntvs_analysis.dat 264 | node_modules/ 265 | 266 | # Visual Studio 6 build log 267 | *.plg 268 | 269 | # Visual Studio 6 workspace options file 270 | *.opt 271 | 272 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 273 | *.vbw 274 | 275 | # Visual Studio LightSwitch build output 276 | **/*.HTMLClient/GeneratedArtifacts 277 | **/*.DesktopClient/GeneratedArtifacts 278 | **/*.DesktopClient/ModelManifest.xml 279 | **/*.Server/GeneratedArtifacts 280 | **/*.Server/ModelManifest.xml 281 | _Pvt_Extensions 282 | 283 | # Paket dependency manager 284 | .paket/paket.exe 285 | paket-files/ 286 | 287 | # FAKE - F# Make 288 | .fake/ 289 | 290 | # JetBrains Rider 291 | .idea/ 292 | *.sln.iml 293 | 294 | # CodeRush 295 | .cr/ 296 | 297 | # Python Tools for Visual Studio (PTVS) 298 | __pycache__/ 299 | *.pyc 300 | 301 | # Cake - Uncomment if you are using it 302 | # tools/** 303 | # !tools/packages.config 304 | 305 | # Tabs Studio 306 | *.tss 307 | 308 | # Telerik's JustMock configuration file 309 | *.jmconfig 310 | 311 | # BizTalk build output 312 | *.btp.cs 313 | *.btm.cs 314 | *.odx.cs 315 | *.xsd.cs 316 | 317 | # OpenCover UI analysis results 318 | OpenCover/ 319 | 320 | # Azure Stream Analytics local run output 321 | ASALocalRun/ 322 | 323 | # MSBuild Binary and Structured Log 324 | *.binlog 325 | 326 | # NVidia Nsight GPU debugger configuration file 327 | *.nvuser 328 | 329 | # MFractors (Xamarin productivity tool) working folder 330 | .mfractor/ 331 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Lurler 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # VirtualFileSystem 2 | As the name implies **Virtual File System** (VFS) is a framework to create a virtual file system which allow you to include ("mount") several folders or zipped archives in a specific order merging their file structure and creating a unified file hierarchy while (virtually) overriding any files that have the same paths. 3 | 4 | It could be used as a basis for modding/DLC/addon system in your game where you (or people modding your game) can override existing files of the base game with updated versions or add new files into the hierarchy seamlessly. 5 | 6 | Note on file overridding: if you include "mod1" that contains "folder1/file1.txt" and then include "mod2" which contains a different file but with with the same path "folder1/file1.txt" it will then be overriden since mod2 was included after mod1. Similar approach to modding is actually already present in a large number of games. Additionally, as stated above this approach can also be used not only for modding, but to allow loading of additional content (e.g. DLC) or any other extra data into the game. 7 | 8 | **Virtual File System** supports both: folders and zipped archives, and is developed in pure C# with no external dependencies. 9 | 10 | The goal of this framework is to make adding mod support to games as easy as it can possibly be. It offers a clean, minimalist, and fully documented API that is easy to learn and use. 11 | 12 | ## Installation 13 | Use provided nuget package or download the source. 14 | 15 | [![NuGet](https://img.shields.io/nuget/v/VirtualFileSystem.svg?style=for-the-badge)](https://www.nuget.org/packages/VirtualFileSystem) 16 | 17 | :wrench: `dotnet add package VirtualFileSystem` 18 | 19 | ## Quick start 20 | First, create a new vfs container and add any number of root folders (at least one is required). 21 | 22 | ```cs 23 | // Create VFS and include several root containers 24 | var vfs = new VFSManager(); 25 | vfs.AddRootContainer("Data/ModFolder1"); // folder with the name "ModFolder1" 26 | vfs.AddRootContainer("Data/ModFolder2"); // folder with the name "ModFolder2" 27 | vfs.AddRootContainer("Data/Mod3.pak"); // zip archive with the name "Mod3.pak" 28 | ``` 29 | 30 | Next... well, that's it! Now you can read files from the VFS as needed :) 31 | 32 | ```cs 33 | // check if file exists 34 | bool fileExists = vfs.FileExists(virtualPath); 35 | 36 | // check if folder exists 37 | bool folderExists = vfs.FolderExists(virtualPath); 38 | 39 | // get file stream 40 | Stream stream = vfs.GetFileStream(virtualPath); 41 | 42 | // get all contents of the file as byte array 43 | byte[] content = vfs.GetFileContents(virtualPath); 44 | 45 | // or if it's a text file - get the text directly 46 | string text = GetFileContentsAsText(virtualPath); 47 | 48 | // you can get a list of all entry paths (virtual files) 49 | List allEntries = vfs.Entries; 50 | 51 | // you can get a list of all folders 52 | List allFolders = vfs.Folders; 53 | 54 | // you can also get all files in a specific folder 55 | List filesInFolder = vfs.GetFilesInFolder(virtualPath); 56 | 57 | // same as above, but you can also filter by extension 58 | List filesInFolderWithExtension = vfs.GetFilesInFolder(virtualPath, "txt"); 59 | 60 | // ...and there are a few more functions you can call. 61 | ``` 62 | 63 | ## Notes 64 | - Paths are non case sensitive. "Some/Path/To/File.txt" is the same as "some/path/to/file.txt". 65 | 66 | ## Changes 67 | - v1.3.2 - Fixed bugs with files and folders lookup. Fixed test project target framework. Improved test project. 68 | - v1.3.1 - Switched to netstandard2.0 to improve compatibility. 69 | - v1.3 - Recursive search, ability to read text directly, ability to work with folders, etc. 70 | - v1.2 - Some refactoring and improvements based on feedback received. 71 | - v1.1 - Added folder indexing, some edge case checks and some minor improvements. 72 | - v1.0 - Initial release. 73 | 74 | ## Contribution 75 | Contributions are welcome! 76 | 77 | You can start with submitting an [issue on GitHub](https://github.com/Lurler/VirtualFileSystem/issues). 78 | 79 | ## License 80 | **Virtual File System** is released under the [MIT License](../master/LICENSE). -------------------------------------------------------------------------------- /VFSTest/Data/Mod1.pak/file1.txt: -------------------------------------------------------------------------------- 1 | file1 in mod1 -------------------------------------------------------------------------------- /VFSTest/Data/Mod1.pak/file2.txt: -------------------------------------------------------------------------------- 1 | file2 in mod1 -------------------------------------------------------------------------------- /VFSTest/Data/Mod2.pak/file2.txt: -------------------------------------------------------------------------------- 1 | file2 in mod2 -------------------------------------------------------------------------------- /VFSTest/Data/Mod2.pak/folder/file3.txt: -------------------------------------------------------------------------------- 1 | file3 in mod2/folder -------------------------------------------------------------------------------- /VFSTest/Data/Mod2.pak/folder/subfolder/file6.txt: -------------------------------------------------------------------------------- 1 | file6 in mod2/folder/subfolder/ -------------------------------------------------------------------------------- /VFSTest/Data/Mod2.pak/folder/subfolder/sub-sub-folder/file7.txt: -------------------------------------------------------------------------------- 1 | file7 in mod2/folder/subfolder/sub-sub-folder/ -------------------------------------------------------------------------------- /VFSTest/Data/Mod3.pak: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Lurler/VirtualFileSystem/349b28483a7fb812faed281ddb4f8d80812e8cb2/VFSTest/Data/Mod3.pak -------------------------------------------------------------------------------- /VFSTest/Program.cs: -------------------------------------------------------------------------------- 1 | using VirtualFileSystem; 2 | 3 | namespace VFSTest; 4 | 5 | class Program 6 | { 7 | 8 | static void Main() 9 | { 10 | // Create VFS and include several mod folders 11 | var vfs = new VFSManager(); 12 | vfs.AddRootContainer("Data/Mod1.pak"); // folder with the name "Mod1.pak" 13 | vfs.AddRootContainer("Data/Mod2.pak"); // folder with the name "Mod2.pak" 14 | vfs.AddRootContainer("Data/Mod3.pak"); // zip archive with the name "Mod3.pak" 15 | 16 | // first display all files 17 | Console.WriteLine("Entries in VFS: "); 18 | foreach (var item in vfs.Entries) 19 | { 20 | Console.WriteLine("> " + item); 21 | } 22 | Console.WriteLine(); 23 | 24 | // and also folders 25 | Console.WriteLine("Folders in VFS: "); 26 | foreach (var item in vfs.Folders) 27 | { 28 | Console.WriteLine("> " + item); 29 | } 30 | Console.WriteLine(); 31 | 32 | // iterate over all of the files and get their contents 33 | Console.WriteLine("Reading file contents: "); 34 | foreach (string path in vfs.Entries) 35 | { 36 | // get file stream 37 | var stream = vfs.GetFileStream(path); 38 | 39 | // convert it to text reader 40 | TextReader textReader = new StreamReader(stream); 41 | 42 | // read all text 43 | var text = textReader.ReadToEnd(); 44 | 45 | // display the text 46 | Console.WriteLine("Virtual path [" + path + "] -> \"" + text + "\""); 47 | } 48 | 49 | // also we can check to see if a particular file exists in the VFS 50 | var nonExistentFilePath = "non-existent-file.txt"; 51 | if (vfs.FileExists(nonExistentFilePath)) 52 | { 53 | Console.WriteLine("File [" + nonExistentFilePath + "] exists."); 54 | } 55 | else 56 | { 57 | Console.WriteLine("File [" + nonExistentFilePath + "] does not exist."); 58 | } 59 | Console.WriteLine(); 60 | 61 | // count files 62 | Console.WriteLine("Files count in folder [] -> " + vfs.GetFilesInFolder("").Count); 63 | Console.WriteLine("Files count in folder [/] -> " + vfs.GetFilesInFolder("/").Count); 64 | Console.WriteLine("Files count in folder [folder] -> " + vfs.GetFilesInFolder("folder").Count); 65 | Console.WriteLine("Files count in folder [folder/] -> " + vfs.GetFilesInFolder("folder/").Count); 66 | Console.WriteLine("Files count in folder [folder2] -> " + vfs.GetFilesInFolder("folder2").Count); 67 | Console.WriteLine("Files count in folder [folder2/] -> " + vfs.GetFilesInFolder("folder2/").Count); 68 | Console.WriteLine("Files count in folder [] with extension [txt] -> " + vfs.GetFilesInFolder("", "txt").Count); 69 | Console.WriteLine(); 70 | 71 | // check recursion 72 | Console.WriteLine("Get file list:"); 73 | var list1 = vfs.GetFilesInFolder("",false); 74 | Console.WriteLine("Files in root no recursion: " + string.Join(", ", list1)); 75 | var list2 = vfs.GetFilesInFolder("", true); 76 | Console.WriteLine("Files in root with recursion: " + string.Join(", ", list2)); 77 | var list3 = vfs.GetFilesInFolder("folder/",false); 78 | Console.WriteLine("Files in \"folder\" folder no recursion: " + string.Join(", ", list3)); 79 | var list4 = vfs.GetFilesInFolder("folder/", true); 80 | Console.WriteLine("Files in \"folder\" folder with recursion: " + string.Join(", ", list4)); 81 | Console.WriteLine(); 82 | 83 | // check recursion 2 84 | Console.WriteLine("Get folder list:"); 85 | var list5 = vfs.GetFoldersInFolder("", false); 86 | Console.WriteLine("Folders in root no recursion: " + string.Join(", ", list5)); 87 | var list6 = vfs.GetFoldersInFolder("", true); 88 | Console.WriteLine("Folders in root with recursion: " + string.Join(", ", list6)); 89 | var list7 = vfs.GetFoldersInFolder("folder/", false); 90 | Console.WriteLine("Folders in \"folder\" no recursion: " + string.Join(", ", list7)); 91 | var list8 = vfs.GetFoldersInFolder("folder/", true); 92 | Console.WriteLine("Folders in \"folder\" with recursion: " + string.Join(", ", list8)); 93 | 94 | Console.ReadLine(); 95 | } 96 | 97 | } 98 | -------------------------------------------------------------------------------- /VFSTest/VFSTest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | enable 8 | 10.0 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | Always 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /VirtualFileSystem.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.4.33213.308 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VirtualFileSystem", "VirtualFileSystem\VirtualFileSystem.csproj", "{506709BF-EF2B-41DC-9FB2-3450D01FAE41}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VFSTest", "VFSTest\VFSTest.csproj", "{D8C040D8-28E7-4785-AF22-F306F9F99796}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {506709BF-EF2B-41DC-9FB2-3450D01FAE41}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {506709BF-EF2B-41DC-9FB2-3450D01FAE41}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {506709BF-EF2B-41DC-9FB2-3450D01FAE41}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {506709BF-EF2B-41DC-9FB2-3450D01FAE41}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {D8C040D8-28E7-4785-AF22-F306F9F99796}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {D8C040D8-28E7-4785-AF22-F306F9F99796}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {D8C040D8-28E7-4785-AF22-F306F9F99796}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {D8C040D8-28E7-4785-AF22-F306F9F99796}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {A35E1D1F-C1CA-4299-B703-EC827562120F} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /VirtualFileSystem/BaseVirtualFile.cs: -------------------------------------------------------------------------------- 1 | namespace VirtualFileSystem; 2 | 3 | internal abstract class BaseVirtualFile 4 | { 5 | internal abstract Stream GetFileStream(); 6 | 7 | internal byte[] GetData() 8 | { 9 | using var ms = new MemoryStream(); 10 | GetFileStream().CopyTo(ms); 11 | return ms.ToArray(); 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /VirtualFileSystem/VFSManager.cs: -------------------------------------------------------------------------------- 1 | using System.IO.Compression; 2 | using System.Text; 3 | 4 | namespace VirtualFileSystem; 5 | 6 | /// 7 | /// Virtual File System (VFS) manager 8 | /// 9 | public class VFSManager 10 | { 11 | /// 12 | /// Stores paths to all files in the VFS with newer files overriding the existing files as they are loaded 13 | /// if the virtual paths collide. 14 | /// 15 | private readonly Dictionary virtualFiles = new(StringComparer.OrdinalIgnoreCase); 16 | 17 | /// 18 | /// Stores all folders that exist in the VFS with at least one file. 19 | /// 20 | private readonly HashSet virtualFolders = new(StringComparer.OrdinalIgnoreCase); 21 | 22 | /// 23 | /// Get a list of all virtual file entries in the VFS. 24 | /// 25 | public List Entries => virtualFiles.Keys.ToList(); 26 | 27 | /// 28 | /// Get a list of all virtual folders in the VFS. 29 | /// 30 | public List Folders => virtualFolders.ToList(); 31 | 32 | /// 33 | /// Adds a new root container which can be either a folder on the hard drive or a zip file. 34 | /// 35 | public void AddRootContainer(string path) 36 | { 37 | // check if it's a zipped container 38 | if (File.Exists(path)) 39 | { 40 | IncludeArchive(path); 41 | return; 42 | } 43 | 44 | // check if it's just a folder 45 | if (Directory.Exists(path)) 46 | { 47 | IncludeFolder(path); 48 | return; 49 | } 50 | 51 | // otherwise incorrect path provided 52 | throw new ArgumentException("Incorrect path provided."); 53 | } 54 | 55 | /// 56 | /// Formats virtual path to be uniform, so there are no identical entries but with different paths. 57 | /// 58 | private string NormalizePath(string path) 59 | { 60 | return path 61 | .Replace(@"\\", @"\") 62 | .Replace(@"\", @"/"); 63 | } 64 | 65 | private void IncludeArchive(string path) 66 | { 67 | try 68 | { 69 | // try opening the archive and iterate over all entries there 70 | var zip = ZipFile.OpenRead(path); 71 | foreach (var entry in zip.Entries) 72 | { 73 | // skip directories 74 | if (entry.FullName.Last() == '/') 75 | continue; 76 | 77 | // standardize slashes 78 | var virtualPath = NormalizePath(entry.FullName); 79 | 80 | // create a virtual file, then add or replace it in the dictionary 81 | virtualFiles[virtualPath] = new VirtualZippedFile(zip, entry.FullName); 82 | 83 | // register virtual folder if it isn't registered yet 84 | var virtualFolder = NormalizePath(Path.GetDirectoryName(virtualPath) ?? ""); 85 | if (!string.IsNullOrEmpty(virtualFolder) && !virtualFolders.Contains(virtualFolder + "/", StringComparer.OrdinalIgnoreCase)) 86 | virtualFolders.Add(virtualFolder + "/"); 87 | } 88 | } 89 | catch (InvalidDataException ex) 90 | { 91 | throw new ArgumentException("The zip archive is invalid.", ex); 92 | } 93 | catch (IOException ex) 94 | { 95 | throw new ArgumentException("Failed to access the zip archive.", ex); 96 | } 97 | catch (Exception ex) 98 | { 99 | throw new ArgumentException("Incorrect container. The vfs container must be a folder or a zip archive.", ex); 100 | } 101 | } 102 | 103 | private void IncludeFolder(string path) 104 | { 105 | // load complete file list into the list 106 | int rootLength = path.Length + (path.EndsWith(@"\") ? 0 : 1); 107 | var files = 108 | Directory.GetFiles(path, "*", SearchOption.AllDirectories) 109 | .Select(p => p.Remove(0, rootLength)) 110 | .ToList(); 111 | 112 | // go through all of the files that were found 113 | foreach (string file in files) 114 | { 115 | // standardize slashes 116 | var relativePath = NormalizePath(file); 117 | 118 | // create a virtual file, then add or replace it in the dictionary 119 | virtualFiles[relativePath] = new VirtualOSFile(path + "/" + file); 120 | 121 | // register virtual folder if it isn't registered yet 122 | var virtualFolder = NormalizePath(Path.GetDirectoryName(relativePath) ?? ""); 123 | if (!string.IsNullOrEmpty(virtualFolder) && !virtualFolders.Contains(virtualFolder + "/", StringComparer.OrdinalIgnoreCase)) 124 | virtualFolders.Add(virtualFolder + "/"); 125 | } 126 | 127 | } 128 | 129 | /// 130 | /// Checks if a file with a given virtual path exists in the VFS. 131 | /// 132 | public bool FileExists(string virtualPath) 133 | { 134 | return virtualFiles.ContainsKey(NormalizePath(virtualPath)); 135 | } 136 | 137 | /// 138 | /// Checks if a folder with a given virtual path exists in the VFS. 139 | /// 140 | public bool FolderExists(string virtualPath) 141 | { 142 | // add final slash if needed 143 | if (!virtualPath.EndsWith("/")) 144 | virtualPath += '/'; 145 | 146 | return virtualFolders.Contains(NormalizePath(virtualPath)); 147 | } 148 | 149 | /// 150 | /// Returns a stream to a file with a given virtual path. 151 | /// 152 | public Stream GetFileStream(string virtualPath) 153 | { 154 | if (!virtualFiles.TryGetValue(NormalizePath(virtualPath), out BaseVirtualFile? value)) 155 | { 156 | throw new FileNotFoundException($"The virtual file '{virtualPath}' does not exist."); 157 | } 158 | return value.GetFileStream(); 159 | } 160 | 161 | /// 162 | /// Read all data from the file and return it as an array of bytes. 163 | /// 164 | public byte[] GetFileContents(string virtualPath) 165 | { 166 | if (!virtualFiles.TryGetValue(NormalizePath(virtualPath), out BaseVirtualFile? value)) 167 | { 168 | throw new FileNotFoundException($"The virtual file '{virtualPath}' does not exist."); 169 | } 170 | return value.GetData(); 171 | } 172 | 173 | /// 174 | /// Read all data from the file and return it as text. 175 | /// 176 | public string GetFileContentsAsText(string virtualPath, Encoding? encoding = null) 177 | { 178 | encoding ??= Encoding.UTF8; // defaults to UTF-8 if no encoding is provided 179 | using var stream = GetFileStream(virtualPath); 180 | using var reader = new StreamReader(stream, encoding); 181 | return reader.ReadToEnd(); 182 | } 183 | 184 | /// 185 | /// Get list of files in a given folder (list of their paths). 186 | /// 187 | public List GetFilesInFolder(string virtualPath, bool recursive = false) 188 | { 189 | // add final slash if needed 190 | if (virtualPath.Length == 0 || virtualPath.Last() != '/') 191 | virtualPath += '/'; 192 | 193 | // check if we want files in root folder 194 | if (virtualPath == "/") 195 | return recursive 196 | ? virtualFiles.Keys.ToList() 197 | : virtualFiles.Keys.Where(s => !s.Contains('/')).ToList(); 198 | 199 | // return empty list if no such path exists 200 | if (!virtualFolders.Contains(virtualPath)) 201 | return new(); 202 | 203 | // finally get the file list (if any) 204 | return virtualFiles.Keys 205 | .Where(s => recursive 206 | ? s.StartsWith(virtualPath, StringComparison.OrdinalIgnoreCase) 207 | : s.StartsWith(virtualPath, StringComparison.OrdinalIgnoreCase) && s.IndexOf('/', virtualPath.Length) == -1) 208 | .ToList(); 209 | } 210 | 211 | /// 212 | /// Get list of folders in a given folder (list of paths). 213 | /// 214 | public List GetFoldersInFolder(string virtualPath, bool recursive = false) 215 | { 216 | // add final slash if needed 217 | if (virtualPath.Length > 0 && virtualPath.Last() != '/') 218 | virtualPath += '/'; 219 | 220 | return virtualFolders 221 | .Where(s => recursive 222 | ? s.StartsWith(virtualPath) && !s.Equals(virtualPath, StringComparison.OrdinalIgnoreCase) 223 | : IsDirectChild(virtualPath, s)) // non-recursive: only match folders directly in the folder 224 | .ToList(); 225 | } 226 | 227 | /// 228 | /// Determines if a folder is a direct child of the given parent folder. 229 | /// 230 | private bool IsDirectChild(string parentPath, string childPath) 231 | { 232 | if (!childPath.StartsWith(parentPath, StringComparison.OrdinalIgnoreCase)) 233 | return false; 234 | 235 | // Get the remaining part of the child path after the parent path 236 | return (childPath.Substring(parentPath.Length)).Count(c => c == '/') == 1; 237 | } 238 | 239 | /// 240 | /// Get list of files in a given folder (list of paths) with additional extension filtering. 241 | /// Extension string must be provided without a dot. 242 | /// 243 | public List GetFilesInFolder(string virtualPath, string extension, bool recursive = false) 244 | { 245 | return GetFilesInFolder(virtualPath, recursive) 246 | .Where(s => s.EndsWith("." + extension, StringComparison.OrdinalIgnoreCase)) 247 | .ToList(); 248 | } 249 | 250 | } 251 | -------------------------------------------------------------------------------- /VirtualFileSystem/VirtualFileSystem.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | netstandard2.0 5 | enable 6 | 10.0 7 | enable 8 | True 9 | VirtualFileSystem 10 | Virtual File System (VFS) is framework to create in-memory virtual file system from folders or zipped archives in a specific order merging their file structure and creating unified file hierarchy while (virtually) overriding any files that have identical paths. 11 | https://github.com/Lurler/VirtualFileSystem 12 | git 13 | README.md 14 | LICENSE 15 | 1.3.2 16 | 17 | 18 | 19 | 20 | True 21 | \ 22 | 23 | 24 | True 25 | \ 26 | 27 | 28 | 29 | 30 | -------------------------------------------------------------------------------- /VirtualFileSystem/VirtualOSFile.cs: -------------------------------------------------------------------------------- 1 | namespace VirtualFileSystem; 2 | 3 | /// 4 | /// Concrete implementation for a virtual file. 5 | /// This implementation is for accessing files on the hard drive. 6 | /// 7 | internal class VirtualOSFile : BaseVirtualFile 8 | { 9 | private readonly string accessPath; 10 | 11 | internal VirtualOSFile(string accessPath) 12 | { 13 | this.accessPath = accessPath; 14 | } 15 | 16 | internal override Stream GetFileStream() 17 | { 18 | return new FileStream(accessPath, FileMode.Open, FileAccess.Read, FileShare.None); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /VirtualFileSystem/VirtualZippedFile.cs: -------------------------------------------------------------------------------- 1 | using System.IO.Compression; 2 | 3 | namespace VirtualFileSystem; 4 | 5 | /// 6 | /// Concrete implementation for a virtual file. 7 | /// This implementation is for accessing files inside an archive. 8 | /// 9 | internal class VirtualZippedFile : BaseVirtualFile 10 | { 11 | private readonly string accessPath; 12 | private readonly ZipArchive zipArchive; 13 | 14 | internal VirtualZippedFile(ZipArchive zipArchiveReference, string accessPath) 15 | { 16 | this.zipArchive = zipArchiveReference; 17 | this.accessPath = accessPath; 18 | } 19 | 20 | internal override Stream GetFileStream() 21 | { 22 | return zipArchive.GetEntry(accessPath)?.Open() 23 | ?? throw new InvalidOperationException("File does not exist in the archive."); 24 | } 25 | } 26 | --------------------------------------------------------------------------------